MFC 创建XML

void CreateXml()
{
    CoInitialize(NULL);
    // 创建文档
    MSXML2::IXMLDOMDocument2Ptr pXMLDoc = NULL;
    //创建DOMDocument对象
    HRESULT hr = pXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument));
    if (!SUCCEEDED(hr))
    {
        return;
    }
    // Create the Processing Instruction
    MSXML2::IXMLDOMProcessingInstructionPtr pXMLProc = NULL;
    pXMLProc = pXMLDoc->createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
    
    _variant_t vNullVal;
    vNullVal.vt = VT_NULL;
    pXMLDoc->insertBefore(pXMLProc, vNullVal);
    // 创建根结点
    _variant_t varNodeType((short)MSXML2::NODE_ELEMENT);
    MSXML2::IXMLDOMNodePtr pXMLNodeRoot= NULL; 
    pXMLNodeRoot = pXMLDoc->createNode(varNodeType, _T("Cases"), _T(""));
    // 添加根结点
    pXMLDoc->appendChild(pXMLNodeRoot);
    // 创建并添加下级结点
    MSXML2::IXMLDOMNodePtr pXMLNodeNode= NULL; 
    pXMLNodeNode = pXMLNodeRoot->appendChild(pXMLDoc->createElement(_T("Case")));
    // 创建下级元素结点
    MSXML2::IXMLDOMElementPtr pXMLEle = NULL;
    pXMLEle = pXMLDoc->createElement(_T("CopyFile"));
    // 创建并设置下级结点属性
    MSXML2::IXMLDOMAttributePtr pXMLAttr = NULL;
    pXMLAttr = pXMLDoc->createAttribute(_T("src"));
    pXMLAttr->nodeTypedValue = "C:\\test.txt";
    pXMLEle->attributes->setNamedItem(pXMLAttr);
    pXMLAttr = pXMLDoc->createAttribute(_T("dest"));
    pXMLAttr->nodeTypedValue = "D:\\Test.txt";
    pXMLEle->attributes->setNamedItem(pXMLAttr);
    // 添加元素结点
    pXMLNodeNode->appendChild( pXMLEle);
    MSXML2::IXMLDOMElementPtr pXMLEle1 = NULL;
    pXMLEle1 = pXMLDoc->createElement(_T("DelFile"));
    pXMLEle1->appendChild(pXMLDoc->createTextNode("C:\\test.txt"));
    // 添加元素结点
    pXMLNodeNode->appendChild( pXMLEle1);
  
    // 保存文档
    pXMLDoc->save(_T("d:\\Test.xml"));
}

效果如下:

<?xml version="1.0" encoding="UTF-8" ?> 
<Cases>
    <Case>
        <CopyFile src="C:\test.txt" dest="D:\Test.txt" /> 
        <DelFile>C:\test.txt</DelFile> 
    </Case>
</Cases>

 

posted @ 2016-11-20 13:11  高山百川  阅读(2260)  评论(0编辑  收藏  举报