VC创建XML文件

XML文件清晰,通用性强。以下代码在VS2008下调试通过。

 

//包括msxml头文件
#include 
//引入msxml动态链接库
#pragma comment(lib,"comsuppwd.lib")


//创建XML文件
void PublicParseXML::CreateXML(CString strFileName)
{	
	CoInitialize(NULL);

	CComPtr  pXmlDoc;
	CComPtr	pXmlProInstruction;
	CComPtr pXmlRoot;
	CComPtr pXmlComment;
	
	CComPtr pXmlPage_1;
	CComPtr pXmlPage_2;

	CComPtr pXmlCtrl_1;
	CComPtr pXmlCtrl_2;

	HRESULT hr = pXmlDoc.CoCreateInstance(_uuidof(DOMDocument));
	if(!SUCCEEDED(hr)) 
	{         
		AfxMessageBox("创建DOMDocument对象失败");
		return;
	}

	//属性设置
	/*pXmlDoc->put_preserveWhiteSpace(VARIANT_TRUE);
	pXmlDoc->put_async(VARIANT_FALSE);
	pXmlDoc->put_validateOnParse(VARIANT_FALSE);
	pXmlDoc->put_resolveExternals(VARIANT_FALSE);*/

	//添加xml说明
	pXmlDoc->createProcessingInstruction(OLESTR("xml"), OLESTR("version=\"1.0\" encoding=\"utf-8\""), &pXmlProInstruction);
	pXmlDoc->appendChild(pXmlProInstruction, NULL);

	//创建添加根节点
	pXmlDoc->createElement(OLESTR("Root"), &pXmlRoot);
	pXmlDoc->appendChild(pXmlRoot, NULL);

	//添加根结点属性
	pXmlRoot->setAttribute(OLESTR("type"), CComVariant(OLESTR("wxp")));
	
	//添加注释
	pXmlDoc->createComment(OLESTR("this is a test"), &pXmlComment);
	pXmlRoot->appendChild(pXmlComment, NULL);

	//创建node1
	pXmlDoc->createElement(OLESTR("test1"), &pXmlCtrl_1);
	//设置节点属性
	pXmlCtrl_1->setAttribute(OLESTR("type"), CComVariant(OLESTR("txt11")));
	pXmlCtrl_1->setAttribute(OLESTR("name"), CComVariant(OLESTR("gsy11")));
	//设置节点内容
	pXmlCtrl_1->put_text(OLESTR("test1_value11"));
	pXmlRoot->appendChild(pXmlCtrl_1, NULL);

	//创建node2
	pXmlDoc->createElement(OLESTR("test2"), &pXmlCtrl_2);
	pXmlCtrl_2->setAttribute(OLESTR("type"), CComVariant(OLESTR("txt22")));
	pXmlCtrl_2->setAttribute(OLESTR("name"), CComVariant(OLESTR("ttt22")));
	//pXmlCtrl_2->put_text(OLESTR("test2_value22"));
	pXmlRoot->appendChild(pXmlCtrl_2, NULL);

	//创建孩子的孩子
	pXmlDoc->createElement(OLESTR("child"), &pXmlCtrl_1);
	pXmlCtrl_1->setAttribute(OLESTR("type"), CComVariant(OLESTR("txt22")));
	pXmlCtrl_1->setAttribute(OLESTR("name"), CComVariant(OLESTR("ttt22")));
	pXmlCtrl_1->put_text(OLESTR("child"));
	pXmlCtrl_2->appendChild(pXmlCtrl_1, NULL);


	//创建属性
	//pXmlDoc->createAttribute(OLESTR("type"), &pXmlAttr_1);
	//pXmlAttr_1->put_value(CComVariant(OLESTR("txt")));
	
	//保存为xml
	pXmlDoc->save(CComVariant(OLESTR("test.xml")));
	
	CoUninitialize();
}

 

你可能感兴趣的