【原创】C++利用IXMLDOM解析XML文件。

项目是在wince平台下做的,但是解析过程和代码却别不大,贴出代码,留做备份。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// TestIXML.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <windows.h>
#include <comutil.h>
#include <stdlib.h>
#include <stdio.h>
#include <MsXml2.h>
 
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
 
void TestXML();
void TestSound();
 
 
#define TIROSLIB_DBG_FILE "\\Test_Pro.log"
 
void dbgprintf(const char *str, ...)
{
    va_list ap;
    FILE *fh = NULL;
 
    if(fh = fopen(TIROSLIB_DBG_FILE, "a"))
    {
        va_start(ap, str);
        vfprintf(fh, str, ap);
        fprintf(fh, "\n");
        va_end(ap);
        fclose(fh);
        fh = NULL;
    }
}
 
 
typedef struct _weather_info_node
{
    char szDate[32];
    char szCondition[5];
    char szWind[32];
    float fLowTemp;
    float fHighTemp;
    int nReserved;
    struct _weather_info_node *lpNext; 
}weather_info_node;
 
weather_info_node *m_lpWeatherNode = NULL;
 
weather_info_node *NewWeatherNode()
{
    weather_info_node *newNode = (weather_info_node *)malloc(sizeof(weather_info_node));
 
    memset(newNode, 0, sizeof(weather_info_node));
 
    newNode->lpNext = NULL;
 
    return newNode;
}
 
void DestoryWeatherList(weather_info_node **weatherList)
{
    weather_info_node *DElem, *next;
 
    DElem = *weatherList;
 
    while(DElem)
    {
        next = DElem->lpNext;
        free(DElem);
        DElem = next;    
    }
 
    *weatherList = NULL;
}
 
BOOL ParseWeatherXml(const char *lpXmlPath)
{
    //xml节点名的枚举
    enum node_Names{xml_day, xml_low, xml_high, xml_condition, xml_wind};
 
    IXMLDOMDocument *pXMLDocument= NULL;
    IXMLDOMNode *pNode = NULL;
    IXMLDOMNodeList *pNodeList = NULL;
    IXMLDOMNodeList *pChildNodeList = NULL;
    IXMLDOMParseError * pObjError = NULL;
    IXMLDOMNamedNodeMap *pNodeMap = NULL;
    //DOMNodeType nodeType;
 
    VARIANT vXmlPath;
    VARIANT vValue;
    VARIANT_BOOL vbStatus;
    BSTR bstr = NULL;
    long lLength = 0;
 
    weather_info_node *lpTemp = NULL;
 
    int nLen = strlen(lpXmlPath) + 1;
    int nwLen  = MultiByteToWideChar(CP_ACP, 0, lpXmlPath, nLen, NULL, 0);
 
    TCHAR lpSzXmlPath[256];
    MultiByteToWideChar(CP_ACP, 0, lpXmlPath, nLen, lpSzXmlPath, nwLen);
 
    VariantInit(&vXmlPath);
    V_BSTR(&vXmlPath) = SysAllocString(lpSzXmlPath);
    V_VT(&vXmlPath) = VT_BSTR;
 
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
    HRESULT hr  = CoCreateInstance(CLSID_DOMDocument,
        NULL,
        CLSCTX_INPROC_SERVER,
        IID_IXMLDOMDocument2,
        (void**)&pXMLDocument);
 
    hr = pXMLDocument->put_async(VARIANT_FALSE);
    if (FAILED(hr))
    {
        printf("Failed to set async property\n");
    }
 
    hr = pXMLDocument->put_validateOnParse(VARIANT_FALSE);
    if (FAILED(hr))
    {
        printf("Failed to set validateOnParse\n");
    }
 
    hr = pXMLDocument->put_resolveExternals(VARIANT_FALSE);
    if (FAILED(hr))
    {
        printf("Failed to disable resolving externals.\n");
    }
 
    hr = pXMLDocument->load(vXmlPath, &vbStatus);
    if (vbStatus != VARIANT_TRUE)
    {
        hr = pXMLDocument->get_parseError(&pObjError);
        hr = pObjError->get_reason(&bstr);
        printf("Failed to load DOM from books.xml. %S\n",bstr);
    }
 
    hr = pXMLDocument->get_xml(&bstr);
    if(FAILED(hr))
    {
        printf("xml 的内容:\n%S\n", bstr);
        SysFreeString(bstr);
    }
 
    hr = pXMLDocument->selectSingleNode(L"//weather", &pNode);
 
    //hr = pNode->get_nodeName(&bstr);
 
    hr = pNode->get_childNodes(&pNodeList);
 
    hr = pNodeList->get_length(&lLength);
 
    for (int nIndex = 0; nIndex != lLength; ++nIndex)
    {
        if (0 == nIndex)
        {
            m_lpWeatherNode = NewWeatherNode();
            lpTemp = m_lpWeatherNode;
        }
        else
        {
            lpTemp->lpNext = NewWeatherNode();
            lpTemp = lpTemp->lpNext;
        }
 
        hr = pNodeList->get_item(nIndex, &pNode);
        hr = pNode->get_childNodes(&pChildNodeList);
        long lChildLength = 0;
        hr = pChildNodeList->get_length(&lChildLength);
 
        for (int nChildIndex = 0; nChildIndex != lChildLength; ++nChildIndex)
        {
            //hr = pNode->get_nodeName(&bstr);
 
            switch(nChildIndex)
            {
            case xml_day:
                hr = pChildNodeList->get_item(nChildIndex, &pNode);
                hr = pNode->get_attributes(&pNodeMap);
                hr = pNodeMap->get_item(0, &pNode);
                hr = pNode->get_nodeTypedValue(&vValue);
 
                memcpy(lpTemp->szDate, (char *)(_bstr_t)vValue.bstrVal, strlen((char *)(_bstr_t)vValue.bstrVal));
 
                break;
 
            case xml_low:
                hr = pChildNodeList->get_item(nChildIndex, &pNode);
                hr = pNode->get_attributes(&pNodeMap);
                hr = pNodeMap->get_item(0, &pNode);
                hr = pNode->get_nodeTypedValue(&vValue);
 
                lpTemp->fLowTemp = atof((char *)(_bstr_t)vValue.bstrVal);
 
                break;
 
            case xml_high:
                hr = pChildNodeList->get_item(nChildIndex, &pNode);
                hr = pNode->get_attributes(&pNodeMap);
                hr = pNodeMap->get_item(0, &pNode);
                hr = pNode->get_nodeTypedValue(&vValue);
 
                lpTemp->fHighTemp = atof((char *)(_bstr_t)vValue.bstrVal);
 
                break;
 
            case xml_condition:
                hr = pChildNodeList->get_item(nChildIndex, &pNode);
                hr = pNode->get_attributes(&pNodeMap);
                hr = pNodeMap->get_item(0, &pNode);
                hr = pNode->get_nodeTypedValue(&vValue);
 
                memcpy(lpTemp->szCondition, (char *)(_bstr_t)vValue.bstrVal, strlen((char *)(_bstr_t)vValue.bstrVal));
 
                break;
 
            case xml_wind:
                hr = pChildNodeList->get_item(nChildIndex, &pNode);
                hr = pNode->get_attributes(&pNodeMap);
                hr = pNodeMap->get_item(0, &pNode);
                hr = pNode->get_nodeTypedValue(&vValue);
 
                memcpy(lpTemp->szWind, (char *)(_bstr_t)vValue.bstrVal, strlen((char *)(_bstr_t)vValue.bstrVal));
 
                break;
 
            default:
                break;
            }
 
        }
    }
 
    pChildNodeList->Release();
    pNodeMap->Release();
    pNodeList->Release();
    pNode->Release();
    pXMLDocument->Release();
    /*
    hr = pNodeList->get_item(3,&pNode);
 
    hr = pNode->get_attributes(&pMap);
 
    hr = pMap->get_item(0, &pNode);
 
    hr = pNode->get_nodeTypedValue(&vValue);
    */
    return TRUE;
}
void TestMyXml()
{
    char *lpTempPath = "\\Storage Card\\WeatherXML20101122150441.txt";
    ParseWeatherXml(lpTempPath);
    while(m_lpWeatherNode != NULL)
    {
        dbgprintf("Date = %s,Low = %f, High = %f, Condition = %s, Wind = %s",
            m_lpWeatherNode->szDate,
            m_lpWeatherNode->fLowTemp,
            m_lpWeatherNode->fHighTemp,
            m_lpWeatherNode->szCondition,
            m_lpWeatherNode->szWind);
 
        m_lpWeatherNode = m_lpWeatherNode->lpNext;
    }
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    TestMyXml();
    //TestXML();
    return 0;
}
 
 
void TestXML()
{
    IXMLDOMDocument *pXMLDocument= NULL;
    IXMLDOMNode *pNode = NULL;
    IXMLDOMNodeList *pNodeList = NULL;
    IXMLDOMParseError * pObjError = NULL;
    DOMNodeType nodeType;
    IXMLDOMNamedNodeMap *pMap = NULL;
    VARIANT v1;
    VARIANT variantvalue;
    VARIANT_BOOL status;
    BSTR bstr = NULL;
    VariantInit(&v1);
    V_BSTR(&v1) = SysAllocString(L"D:\\WeatherXML20101122150441.txt");
    V_VT(&v1) = VT_BSTR;
 
    // 首先必须调用CoInitialize
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
 
    // 创建一msxml 文档实例,返回IXMLDOMDocument2接口。
    HRESULT hr  = CoCreateInstance(CLSID_DOMDocument,
        NULL,
        CLSCTX_INPROC_SERVER,
        IID_IXMLDOMDocument2,
        (void**)&pXMLDocument);
 
    hr = pXMLDocument->put_async(VARIANT_FALSE);
    if (FAILED(hr)) {
        printf("Failed to set async property\n");
        //goto clean;
    }
 
    hr = pXMLDocument->put_validateOnParse(VARIANT_FALSE);
    if (FAILED(hr)) {
        printf("Failed to set validateOnParse\n");
        //goto clean;
    }
 
    hr = pXMLDocument->put_resolveExternals(VARIANT_FALSE);
    if (FAILED(hr)) {
        printf("Failed to disable resolving externals.\n");
        //goto clean;
    }
 
    hr = pXMLDocument->load(v1, &status);
 
    if (status!=VARIANT_TRUE) {
        hr = pXMLDocument->get_parseError(&pObjError);
        hr = pObjError->get_reason(&bstr);
        printf("Failed to load DOM from books.xml. %S\n",bstr);
        //goto clean;
    }
 
    hr = pXMLDocument->get_xml(&bstr);
    printf("foo.xml 的内容:\n%S\n", bstr);
    SysFreeString(bstr);
 
    hr = pXMLDocument->selectSingleNode(L"//fc", &pNode);
    hr = pNode->get_nodeName(&bstr);
 
    hr = pNode->get_childNodes(&pNodeList);
 
    long length;
    hr = pNodeList->get_length(&length);
    hr = pNodeList->get_item(3,&pNode);
 
    hr = pNode->get_attributes(&pMap);
 
    hr = pMap->get_item(0, &pNode);
 
    hr = pNode->get_nodeTypedValue(&variantvalue);
 
    //hr = pNode->get_childNodes(&pNodeList);
 
    //hr = pNodeList->get_item(0, &pNode);
 
    //hr = pNode->get_nodeType(&nodeType);
 
    //hr = pNode->get_nodeValue(&variantvalue);
 
    //hr = pNode->get_dataType(&variantvalue);
 
 
 
 
    //  hr = pNode->get_xml(&bstr);
 
    //hr = pNode->get_nodeType(&nodeType);
 
    //  variantvalue.vt = nodeType;
 
    //  hr = pNode->get_dataType(&variantvalue);
 
    //  hr = pNode->get_nodeValue(&variantvalue);
 
    //hr = pNode->get_nodeTypedValue(&variantvalue);
 
    //  hr = pNode->get_
    //  if (FAILED(hr)) {
    //      hr = pXMLDocument->get_parseError(&pObjError);
    //      hr = pObjError->get_reason(&bstr);
    //      printf("Failed to load DOM from books.xml. %S\n",bstr);
    //      //goto clean;
    //  }
    //hr = pNode->get_nodeName(&bstr);
    //DOMNodeType nodeType;
 
    //得到节点类型
    //pNode->get_nodeType(&nodeType);
 
    //节点名称
    //
    //  BSTR nodeName;
    //
    //  hr = pNode->get_nodeName(&nodeName);
    //
    //  char *cNodeName = (char *)nodeName;
 
    //cNodeName = ConvertBSTRToString(nodeName);
    //strName=(char *)pNode->GetnodeName();
 
    //节点属性,放在链表中
    //          MSXML2::IXMLDOMNamedNodeMapPtr pAttrMap=NULL;
    //          MSXML2::IXMLDOMNodePtr   pAttrItem;
    //          _variant_t variantvalue;
    //          pNode->get_attributes(&pAttrMap);
    //
    //          long count;
    //          count=pAttrMap->get_length(&count);
    //
    //          pAttrMap->get_item(0,&pAttrItem);
    //          //取得节点的值
    //          pAttrItem->get_nodeTypedvalue(&variantvalue);
    //          m_strId=(char *)(_bstr_t)variantvalue;
    //
    //          UpdateData(FALSE);
 
 
    //hr = pXMLDocument->getProperty(L"<day data/>", &v2);
    //hr = pXMLDocument->save(v1);
    //pXMLDocument->Release();
 
    CoUninitialize();
}

xml文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<weather pd="2010-11-22 08:00:00" xmlns="http://www.xxx.com">
  <fc>
    <day data="2010-11-22 08:00:00"/>
    <low data="-2.0"/>
    <high data="9.0"/>
    <condition data="晴"/>
    <wind data="静风、小于3级"/>
    <indexes>
      <index type="3" data="6"/>
      <index type="4" data="6"/>
      <index type="1" data="1"/>
      <index type="2" data="2"/>
    </indexes>
  </fc>
  <fc>
    <day data="2010-11-23 08:00:00"/>
    <low data="1.0"/>
    <high data="9.0"/>
    <condition data="阴"/>
    <wind data="静风、小于3级"/>
  </fc>
  <fc>
    <day data="2010-11-24 08:00:00"/>
    <low data="-4.0"/>
    <high data="6.0"/>
    <condition data="晴"/>
    <wind data="北风转静风、3级转小于3级"/>
  </fc>
</weather>

posted @   天堂大鸟  阅读(2114)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示