Reputation: 123
I have an XML file, a section of it shown here below.
<node id="413" text="plant1">
<node id="419" text="Detail Reports">
<node id="424" text="Bulk Lactol" reportid="14" nodetype="1"/>
<node id="427" text="Effluent" reportid="17" nodetype="1"/>
<node id="425" text="Pasteurisers" reportid="15" nodetype="1"/>
<node id="421" text="Tank 8" reportid="12" nodetype="1"/>
<node id="420" text="Tank 9" reportid="11" nodetype="1"/>
</node>
<node id="422" text="Summary Reports">
<node id="423" text="plant1 Summary" reportid="13" nodetype="1"/>
<node id="426" text="Effluent Summary" reportid="16" nodetype="1"/>
</node>
</node>
I am trying to get the 'node id' by the 'text' value. I tried the following.
string y = "Bulk Lactol"
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Joe\\Desktop\\wt.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode(y);
string x = Convert.ToString(node);
But I am getting an exception:
'Bulk Lactol' has an invalid token.
I found some similar questions but I am not very familiar with XML so I was having trouble adapting them to my problem, Thanks for any help.
Upvotes: 0
Views: 694
Reputation: 34234
SelectSingleNode
and SelectNodes
accept XPath string as an argument.
You can use the following XPath to find this item:
string y = "Bulk Lactol";
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Joe\\Desktop\\wt.xml");
XmlNode node = doc.SelectSingleNode(@"//node[@text='Bulk Lactol']");
string x = node.InnerText;
//node[@text='Bulk Lactol']
XPath means
any element in the hierarchy which has an attribute "text" with value "Bulk Lactol"
Upvotes: 3