Use a relative path return element.XPathSelectElement("id").Value;
, with //id
you search down from /
which is the document node.
iterating XElements and then using XPath to extract child element values gets wrong value
-
28-09-2022 - |
Question
I have two methods:
- the first one parses a xml string into some XElements (where the xml is a sequence of 'banana' elements)
- the second one extracts the value from a child 'id' element and returns it
I have two alternative implementations of 'GetBananaId(XElement element)' - can anyone explain why the second 'wrong' implementation doesn't give the child element relative to its XElement parameter?
public void TestHarness()
{
var xml = "<bananas><banana><id>A</id></banana><banana><id>B</id></banana><banana><id>C</id></banana></bananas>";
foreach (var element in GetBananaElements(xml))
{
var right = GetBananaId(element);
var wrong = GetBananaId_WRONG(element);
Console.WriteLine("Right: {0}, Wrong: {1}", right, wrong);
}
}
public IEnumerable<XElement> GetBananaElements(string recordsXml)
{
var recordsXDoc = XDocument.Parse(recordsXml);
return recordsXDoc.XPathSelectElements("//banana");
}
public string GetBananaId(XElement element)
{
return element.Element("id").Value;
}
public string GetBananaId_WRONG(XElement element)
{
return element.XPathSelectElement("//id").Value;
}
These produce the console output:
Right: A, Wrong: A
Right: B, Wrong: A
Right: C, Wrong: A
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow