程序代码
- #import "msxml6.dll" named_guids raw_interfaces_only
- #include <msxml.h>
- using namespace MSXML2;
- using namespace std;
- int testXml(wstring strfilname)
- {
- cout << "BEGIN" << endl;
- HRESULT hr;
- long cnt;
- try
- {
- MSXML2::IXMLDOMDocumentPtr pDoc;
- MSXML2::IXMLDOMNodeListPtr pNodeList;
- MSXML2::IXMLDOMNodePtr pNode, pRoot;
- MSXML2::IXMLDOMNamedNodeMapPtr pAttr;
- hr = ::CoInitialize(NULL);
- if (FAILED(hr))
- {
- throw L"failed to com init";
- }
- hr = CoCreateInstance(CLSID_DOMDocument60, NULL, CLSCTX_INPROC_SERVER,
- MSXML2::IID_IXMLDOMDocument, (void**)&pDoc);
- if(FAILED(hr))
- throw "failed to create DOM DOC";
- VARIANT_BOOL bIsSuccessful;
- BSTR bstr1 = SysAllocString(L"d://b.xml");
- VARIANT v1;
- v1.vt = VT_BSTR;
- v1.bstrVal = bstr1;
- ///// 载入 xml文件
- pDoc->load(v1, &bIsSuccessful);
- SysFreeString(bstr1);
- ///// 获取根节点 ROOT_BASENAME
- //pRoot = pDoc->firstChild;
- pDoc->get_firstChild(&pRoot);
- ///// 输出跟节点名字
- BSTR bstr;
- pRoot->get_nodeName(&bstr);
- cout << (char*)((_bstr_t)bstr) <<endl;
- ///// 获取根节点属性 Attr_baseName_1 = "Attr_text_1" Attr_baseName_2 = "Attr_text_2"
- pRoot->get_attributes(&pAttr);
- ///// 取得属性个数
- long length;
- pAttr->get_length(&length);
- cout << length << endl;
- ///// 输出根节点属性
- for(cnt = 0 ; pAttr->nextNode(&pNode), pNode ; ++cnt)
- {
- BSTR baseName;
- pNode->get_baseName(&baseName);
- BSTR text;
- pNode->get_text(&text);
- cout << (char*)((_bstr_t)baseName) << " " << (char*)((_bstr_t)text) << endl;
- }
- cout << "Attr count " << cnt <<endl;
- ///// 输出根节点所有儿子
- pRoot->get_childNodes(&pNodeList);
- pNodeList->get_length(&cnt);
- cout << "LENGTH " << cnt << endl;
- for(cnt = 0; pNodeList->nextNode(&pNode), pNode; ++cnt)
- {
- BSTR text;
- pNode->get_text(&text);
- cout << (char*)((_bstr_t)text) << endl;
- }
- cout << "Node count " << cnt <<endl;
- }
- catch (string str)
- {
- cout << "Exception : " << str << endl;
- }
- catch (...)
- {
- cout << "Exception Unkonwn/n";
- }
- ::CoUninitialize();
- cout << "END" <<endl;
- return 0;
- }
xml文件:
- <ROOT_BASENAME Attr_baseName_1 = "Attr_text_1" Attr_baseName_2 = "Attr_text_2">
- <FIRST_CHILD>
- text_1
- </FIRST_CHILD>
- <CHILD>
- text_2
- </CHILD>
- <LAST_CHILD>
- text_3
- </LAST_CHILD>
- </ROOT_BASENAME>