我想从 xml 文件中读取。我有这个代码:
IXMLDOMDocument *pXMLDom=NULL;
IXMLDOMNodeList *pXMLDomNodeList=NULL;
VARIANT varFileName;
VARIANT_BOOL varStatus;
BSTR bstrNodeValueParent = NULL;
BSTR bstrNodeValueChild = NULL;
CreateAndInitDOM(&pXMLDom);
VariantFromString(L"file.xml", varFileName);
pXMLDom->load(varFileName, &varStatus)
if (varStatus == VARIANT_TRUE){
long lengthNodeList;
BSTR bstrQueryTemp=SysAllocString(L"//parent_tag");
pXMLDom->selectNodes(bstrQueryTemp,&pXMLDomNodeList);
pXMLDomNodeList->get_length(&lengthNodeList);
for(int j=0; j < lengthNodeList; j++){
IXMLDOMNode *pNodeParent = NULL;
IXMLDOMNode *pNodeChild = NULL;
BSTR bstrNodeValueChild;
pXMLDomNodeList->get_item(j, &pNodeParent);
pNodeParent->get_xml(&bstrNodeValueParent);
printf("\n Parent Node: %S",bstrNodeValueParent);
pNodeParent->selectSingleNode(L"//child1_tag",&pNodeChild);
pNodeChild->get_xml(&bstrNodeValueChild);
printf("\n Child Node: %S",bstrNodeValueChild);
SysFreeString(bstrNodeValueParent);
SysFreeString(bstrNodeValueChild);
SAFE_RELEASE(pNodeParent);
SAFE_RELEASE(pNodeChild);
}
}
第一个 printf 在每个迭代情况下返回正确的值,但第二个没有,实际上它返回第一个子元素的值,情况 j==0。为什么?
文件.xml 示例:
<?xml version="1.0"?>
<!--xml file created using XML DOM object.-->
<root created="using dom">
<parent_tag>
<child1_tag>Child1-1</child1_tag>
<child2>Child1-2</child2>
</parent_tag>
<parent_tag>
<child1_tag>Child2-1</child1_tag>
<child2>Child2-2</child2>
</parent_tag>
<parent_tag>
<child1_tag>Child3-1</child1_tag>
<child2>Child3-2</child2>
</parent_tag>
</root>