C++学习(八):Visual studio 2005 C++ MSXML使用示例

#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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值