Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct use of XmlNode.SelectSingleNode(string xpath) in C#?

Tags:

I'm having trouble dealing with some XML file (which is at the end of this post).

I wrote the following code in order to get Job_Id data related to a given Job_Name pattern whose owner Job_Owner is the user running the probram:

List<String> jobID = new List<String>(); XmlNodeList nodes = xml.SelectNodes("//Job"); foreach (XmlNode node in nodes) {     innerNode = node.SelectSingleNode("//Job_Owner"); // SelectSingleNode here always selects the same node, but I thought it should be relative to node, not to nodes     if (!innerNode.InnerText.Contains(Environment.UserName))     {         continue;     }     innerNode = node.SelectSingleNode("//Job_Name");     if (!Regex.IsMatch(innerNode.InnerText, jobNamePattern, RegexOptions.Compiled))     {         continue;     }     innerNode = node.SelectSingleNode("//Job_Id");     jobID.Add(innerNode.InnerText); } 

I would expect that node.SelectSingleNode("//Job_Name") seeks for a tag named Job_Name only under the xml code represented by node.

That is not what it seems to be happening, as it always return the same node, doesn't matter at what step of the foreach it is (i.e. the node selected from the nodes changes, but the node.SelectSingleNode("//Job_Name") always return the same content).

What is wrong with this code?

Thanks in advance!

--

The XML File looks like this:

<Data>     <Job>         <Job_Id>58282.minerva</Job_Id>         <Job_Name>sb_net4_L20_sType1</Job_Name>         <Job_Owner>mgirardis@minerva</Job_Owner>         <!--more tags-->     </Job>     <Job>         <!--etc etc etc-->     </Job>     <!--etc etc etc--> </Data> 
like image 700
Girardi Avatar asked Oct 07 '11 21:10

Girardi


People also ask

What does SelectSingleNode do?

SelectSingleNode(String)Selects the first XmlNode that matches the XPath expression.

How do I find nodes in XML?

To find nodes in an XML file you can use XPath expressions. Method XmlNode. SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.


1 Answers

It's because you're using the '//' syntax in XPath. That specific syntax selects the first node in the document named that. Try looking at https://www.w3schools.com/xml/xpath_syntax.asp for information on XPath syntax.

If you're looking for child nodes, try just using the node name (IE: 'Job_Owner' instead of '//Job_Owner')

like image 156
Infernex87 Avatar answered Oct 09 '22 10:10

Infernex87