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>
SelectSingleNode(String)Selects the first XmlNode that matches the XPath expression.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With