#include "stdafx.h"
#include <Windows.h>
#include <MsXml2.h>
void parserxml()
{
HRESULT hr = NULL;
VARIANT var;
V_VT(&var) = VT_BSTR;
// COM库初始化
CoInitialize(NULL);
//
IXMLDOMDocument* pXMLDoc;
hr = CoCreateInstance(_uuidof(DOMDocument), NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pXMLDoc);
//
IXMLDOMProcessingInstruction* pi;
pXMLDoc->createProcessingInstruction(L"xml", L"version=\"1.0\" encoding=\"utf-8\"", &pi);
pXMLDoc->appendChild(pi, NULL);
//
IXMLDOMComment* commentElement;
pXMLDoc->createComment(L"mybooks_is_the_best_books", &commentElement);
pXMLDoc->appendChild(commentElement, NULL);
//
IXMLDOMElement* rootElement;
pXMLDoc->createElement(L"mybooks", &rootElement);
pXMLDoc->appendChild(rootElement, NULL);
//
IXMLDOMText* testElement;
pXMLDoc->createTextNode(L"\n", &testElement);
rootElement->appendChild(testElement, NULL);
//
IXMLDOMElement* pChildElement;
pXMLDoc->createElement(L"book", &pChildElement);
rootElement->appendChild(pChildElement, NULL);
//
V_BSTR(&var) = SysAllocString(L"C++ programming");
pChildElement->setAttribute(L"book_name", var);
SysFreeString(V_BSTR(&var));
//
IXMLDOMText* testElement1;
pXMLDoc->createTextNode(L"\n", &testElement1);
rootElement->appendChild(testElement1, NULL);
//
pXMLDoc->createElement(L"book", &pChildElement);
rootElement->appendChild(pChildElement, NULL);
//
V_BSTR(&var) = SysAllocString(L"Windows program");
pChildElement->setAttribute(L"book_name", var);
SysFreeString(V_BSTR(&var));
//
IXMLDOMText* testElement2;
pXMLDoc->createTextNode(L"\n", &testElement2);
rootElement->appendChild(testElement2, NULL);
//
BSTR xmlstr;
pXMLDoc->get_xml(&xmlstr);
//
V_BSTR(&var) = SysAllocString(L"d:\\test.xml");
pXMLDoc->save(var);
SysFreeString(V_BSTR(&var));
pXMLDoc->Release();
// COM库反初始化
CoUninitialize();
}
结果:
<?xml version="1.0"?>
<!--mybooks_is_the_best_books-->
<mybooks>
<book book_name="C++ programming"/>
<book book_name="Windows program"/>
</mybooks>