Reputation: 99
Iam trying to get a particular node with value equals my input parameter,my xpath is like this where b is the node I need
string xpath = "/Batches/Measurement/Batch[market=someval]/b";
<?xml version="1.0" encoding="utf-8" ?>
<Batches>
<Measurement>
<Batch>
<market>someval</market>
<b>someval</b>
</Batch>
</Measurement>
</Batches>
var xmlNode = xmlDoc.SelectNodes(xpath);
no nodes retruned always count 0 ,I checked that the xmldoc is loaded properly.
Upvotes: 1
Views: 960
Reputation: 4607
Have you thought about using LINQ to XML?
It is slightly more efficient and shorter clearner syntax for selecting. I know you asked about Xpath so feel free to ignore this. Just making you aware of the option
var doc = XDocument.Load("c:\\tmp\\test.xml");
var result = doc.Descendants().Where(x => x.Element("b") != null)
.Select(x => x.Element("b").Value);
Upvotes: 0
Reputation: 9627
Your xpath is nearly perfect. Only keep in mind const values have to be put in apostrophe:
"/Batches/Measurement/Batch[market='someval']/b"
Update: C# code example:
XmlNodeList nodeList;
nodeList = root.SelectNodes("/Batches/Measurement/Batch[market='someval']/b");
foreach (XmlNode node in nodeList)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
Console.WriteLine(node.ChildNodes[i].InnerText);
}
}
The return value of SelectNodes is a nodeList. You have to iterate through it.
And a little bit shorter:
XmlElement root = doc.DocumentElement;
string text;
text = root.SelectSingleNode("/Batches/Measurement/Batch[market='someval']/b").InnerText;
Console.WriteLine(text);
Upvotes: 4