I want to read from xml file. I have this code:
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);
}
}
The first printf return the correct value in each iteration case, but the second one no, infact it returns the value of first child element, case j==0. Why?
file.xml example:
<?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>
From the XPath specs (emphasis mine):
//para
selects all thepara
descendants of the document root and thus selects allpara
elements in the same document as the context node.
You're passing "//child1_tag"
to selectSingleNode()
in your loop, but this expression will always match the first child1_tag
element in the document, not in the current parent.
Try instead:
pNodeParent->selectSingleNode(L"child1_tag", &pNodeChild);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.