I want to search a specific node within the parent node,
I tried to do it this way:
public string GetNodeValue(XmlNode myNode, string nodeName, string parentName)
{
return myNode.SelectSingleNode("//"+parentName).SelectSingleNode("//"+nodeName).InnerText;
}
private void SetXmlFile(string path)
{
XmlDocument _doc = new XmlDocument();
_doc.Load(path);
foreach (XmlNode node in _doc.SelectNodes("//MyNodeName"))
{
GetNodeValue(node,"NodeChildeName1","NodeParentName2");
}
}
My xml looks like this:
<SomeNode Name="x">
<a>a1</a>
<a>a2</a>
<a>a3</a>
</SomeNode >
<MyNodeName Name="a1">
<NodeParentName1>
<NodeChildeName1>0</NodeChildeName1>
<NodeChildeName2>40</NodeChildeName1>
</NodeParentName1>
<NodeParentName2>
<NodeChildeName1>1000</NodeChildeName1>
<NodeChildeName2>70</NodeChildeName1>
</NodeParentName2>
</MyNodeName >
I do not get the correct value, it seems that he takes the first node that has the name, and not the first node of the parent node. (I get 0 and not 1000)
The // in GetNodeValue is causing your xpath query to start from the root directory. Remove the // from your GetNodeValue method.
public string GetNodeValue(XmlNode myNode, string nodeName, string parentName)
{
return myNode.SelectSingleNode(parentName).SelectSingleNode(nodeName).InnerText;
}
You could also just query the doucment like such:
_doc.SelectSingleNode("//MyNodeName/NodeParentName2/NodeChildeName1").InnerText
By the way, the xml you posted is invalid. NodeChildeName2 has closing tags of NodeChildeName1
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.