//函数体 代码
//参数说明:
//file:XML文件名指针
//root:XML文档根结点
//child_name:XML文档子结点
long GetXmlContent(const char* file,CString root,
CString child_name)
{
CSockChn xml;
HRESULT hrr = CoInitialize(NULL);
if (FAILED(hrr))
{
AfxMessageBox("ERROR - Could not initialize COM library");
return -1;
}
MSXML2::IXMLDOMDocumentPtr doc;
HRESULT hr;
hr=doc.CreateInstance(__uuidof(MSXML2::DOMDocument40));
if(FAILED(hr))
{
AfxMessageBox("ERROR - Create Object Instance Failed!");
return -1;
}
VARIANT_BOOL bl=doc->load(file);
if(bl==S_FALSE)
{
AfxMessageBox("ERROR - Open XML File Failed!");
return -1;
}
MSXML2::IXMLDOMNodePtr node;
CString nn;
nn.Format("//%s",root);
node=doc->selectSingleNode((LPCTSTR)nn);
MSXML2::DOMNodeType ntype;
node->get_nodeType(&ntype);//节点类型
CString name;
name=(char*)node->GetnodeName();//节点名称
MSXML2::IXMLDOMNamedNodeMapPtr pList=NULL;
node->get_attributes(&pList);
long count;
pList->get_length(&count);
for(int i=0;i<count;i++)//获取属性
{
MSXML2::IXMLDOMNodePtr pNode;
pList->get_item(i,&pNode);
_variant_t v;
CString n=(char*)pNode->GetnodeName();
CString va=(char*)(_bstr_t)pNode->GetnodeTypedValue();
}
获取子节点
MSXML2::IXMLDOMNodeListPtr nList;
CString mm;
mm.Format("//%s",child_name);
nList=node->selectNodes((LPCTSTR)mm);
long cc;
nList->get_length(&cc);
for(int i=0;i<cc;i++)
{
CString strid="",strTitle="",strImgid="";
MSXML2::IXMLDOMNodePtr nn=nList->item[i];
CString n=(char*)nn->GetnodeName();
CString va=(char*)(_bstr_t)nn->GetnodeTypedValue();
MSXML2::IXMLDOMNamedNodeMapPtr aList=NULL;
nn->get_attributes(&aList);
long num;
CString attrName,attrValue;
aList->get_length(&num);
for(int m=0;m<num;m++)
{
MSXML2::IXMLDOMNodePtr pNode;
aList->get_item(m,&pNode);
attrName=(char*)pNode->GetnodeName();
attrValue=(char*)(_bstr_t)pNode->GetnodeTypedValue();
if(attrName=="id") strid=attrValue;
else if(attrName=="title") strTitle=attrValue;
else if(attrName=="imgid") strImgid=attrValue;
else ;
}
xml.ipaddress=va;
xml.name=strid;
xml.title=strTitle;
xml.imgid=atoi(strImgid);
sList.AddTail(xml);
}
CoUninitialize();
return cc;
/end
}
//调用方式
GetXmlContent("he.xml","Network","Computer");
//XML文档实例
<?xml version="1.0" encoding="GB2312"?>
<Network id="zt">
<Computer id="xm" title="厦门地区" imgid="2000">10.206.110.54</Computer>
<Computer id="sx" title="山西地区" imgid="2001">10.206.110.20</Computer>
<Computer id="zz" title="福建直通" imgid="2002">10.236.5.224</Computer>
</Network>