您的位置:首页 > 其它

VC操作XML相关知识

2013-05-09 09:35 429 查看
http://www.cnblogs.com/sadier/articles/99875.html

/article/8614488.html

首先需要先安装MSXML4运行库

还需要导入一个MSXML4.dll

再就是在调用前初始化COM库

::CoInitialize(NULL);

CoUninitialize();

核心代码:

MSXML2::IXMLDOMDocumentPtr pDoc;
MSXML2::IXMLDOMElementPtr xmlRoot;
HRESULT hr=pDoc.CreateInstance(_uuidof(MSXML2::DOMDocument40));//先要创建DOC对象
if(!SUCCEEDED(hr))
{
MessageBox( " 无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库! " );
return  ;
}
xmlRoot=pDoc->createElement((_bstr_t)"Book");//再创建根结点,一个XML只能有一个根结点
xmlRoot->setAttribute("id","12345");
pDoc->appendChild(xmlRoot);

MSXML2::IXMLDOMElementPtr pNode;
pNode=pDoc->createElement((_bstr_t)"Author");
pNode->Puttext((_bstr_t)"an jia");
xmlRoot->appendChild(pNode);

pNode=pDoc->createElement("Title");
pNode->Puttext("na na");
xmlRoot->appendChild(pNode);

pDoc->save(".\\Web\\test.xml");
MessageBox("df");


读取XML文件查找指定结点:

MSXML2::IXMLDOMDocumentPtr pDoc;
MSXML2::IXMLDOMElementPtr xmlRoot,node;
HRESULT hr=pDoc.CreateInstance(_uuidof(MSXML2::DOMDocument40));
if(!SUCCEEDED(hr))
{
MessageBox( " 无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库! " );
return  ;
}
pDoc->load(".\\Web\\test.xml");//加载XML文件
MessageBox(pDoc->xml);
xmlRoot=pDoc->GetdocumentElement();//获取的是整个XML的唯一根结点
node=xmlRoot->selectSingleNode((_bstr_t)"//CAM2");//根据名字查找指定结点。。。前面的//指的是在任一根下
MessageBox(node->xml);
xmlRoot->removeChild(node);//删除查找到的根结点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: