本帖最后由 九零-鑫鑫 于 2014-3-18 07:11 编辑
这几天,用VC写一个东西,要用到XML,可是网上XML的东西非常少,还大部分是JavaScript方面的。没办法,只能一点点查,一点点试,终有所获。XP+VC6:
[C++] 纯文本查看 复制代码
首先在系统中加入:
#import "msxml4.dll"
using namespace MSXML2;
然后就可以操作XML文件了。
1、创建xml文件
::CoInitialize(NULL); //初始化COM
MSXML2::IXMLDOMDocumentPtr pDoc;
MSXML2::IXMLDOMElementPtr xmlRoot;
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
MessageBox("Error");
return;
}
pDoc->raw_createElement_x((_bstr_t)(char*)"capture", &xmlRoot);
pDoc->raw_a(xmlRoot, NULL);
MSXML2::IXMLDOMElementPtr childNode;
pDoc->raw_createElement_x((_bstr_t)(char*)"bitmap", &childNode);
xmlRoot->a(childNode);
MSXML2::IXMLDOMElementPtr childNode2;
pDoc->raw_createElement_x((_bstr_t)(char*)"bmp", &childNode2);
childNode2->Puttext("01");
childNode2->setAttribute("population", "7000");
childNode2->setAttribute("area", "2000");
childNode->a(childNode2);
//pDoc->raw_createElement_x((_bstr_t)(char*)"video", &xmlRoot);
pDoc->raw_createElement_x((_bstr_t)(char*)"video", &childNode);
xmlRoot->a(childNode);
pDoc->raw_createElement_x((_bstr_t)(char*)"avi", &childNode2);
childNode2->Puttext("01");
childNode2->setAttribute("population", "39999");
childNode2->setAttribute("area", "3322");
childNode->a(childNode2);
pDoc->save("E:\\test.xml");
生成的XML文件内容如下:
<capture>
<bitmap>
<bmp population="7000" area="2000">01</bmp>
</bitmap>
<video>
<avi population="39999" area="3322">01</avi>
</video>
</capture>
2、浏览XML
::CoInitialize(NULL); //初始化COM
MSXML2::IXMLDOMDocumentPtr pDoc;
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
MessageBox("Error!");
return;
}
pDoc->load("E:\\test.xml");
MSXML2::IXMLDOMElementPtr childNode;
MSXML2::IXMLDOMElementPtr childNode1;
MSXML2::IXMLDOMNodeListPtr nodeList;
MSXML2::IXMLDOMNodeListPtr nodeList1;
childNode1 = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode("//video"));//选中节点
nodeList = childNode1->GetchildNodes();//子节点列表
// MSXML2::DOMNodeType nodeType;
// nodeList=pDoc->getElementsByTagName_r("avi");//获取所有名为avi的节点,可以在bitmap节中介入avi节实验
MSXML2::IXMLDOMNamedNodeMapPtr pAttrs = NULL;
MSXML2::IXMLDOMNodePtr pAttrItem;
MSXML2::IXMLDOMNodePtr pAttrItem1;
long nCount, iCount;
nodeList->get_length(&iCount); //获取节点个数
BOOL bDel = FALSE;
for(int i=0 ;i<iCount; i++) //根据需要可以添加数据到ListControl中
{
childNode = nodeList->Getitem(i).Detach();//得到一个节点
childNode->get_attributes(&pAttrs);
pAttrs->get_length(&nCount); //获取节点属性个数
nodeList->get_item(i, &pAttrItem1);
for(int j = 0; j < nCount; j++)
{
pAttrs->get_item(j, &pAttrItem);
CString strAttrName = (char*)(_bstr_t)pAttrItem->nodeName;
CString strAttrValue = (char*)(_bstr_t)pAttrItem1->nodeTypedValue;
}
}
希望大家多多支持 _(:з」∠)_
|