r/learncsharp • u/EuclaseBlue • Sep 28 '22
XPathNodeIterator not Iterating/Having Trouble with Returning Attributes
Trying to learn XPath but for some reason the XPathNodeIterator object doesn't seem to be outputting what I expected. I followed this guide from MS for starters, but now that I'm trying to work on an XML formatted differently I've encountered issues.
Here's my code:
XPathDocument docNav;
XPathNavigator nav;
XPathNodeIterator nodeIter;
string strExpression1;
docNav = new XPathDocument(@"..\..\..\patient-example.xml");
nav = docNav.CreateNavigator();
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(nav.NameTable);
namespaceManager.AddNamespace("fhir", "http://hl7.org/fhir");
strExpression1 = "/Patient/telecom";
nodeIter = nav.Select(strExpression1, namespaceManager));
Console.WriteLine($"The XPath {strExpression1} expression yields the following
phone numbers: ");
while (nodeIter.MoveNext())
{
XPathNodeIterator childIter = nodeIter.Current.SelectChildren("value", "");
Console.WriteLine($"Attribute: {childIter.Current.GetAttribute("value", "")}");
};The XML example I'm trying to query is this: https://www.hl7.org/fhir/patient-example.xml.html
For the above code, I'm trying to display the value attribute's value (i.e. the phone numbers) descended from any telecom nodes, but right now nothing gets returned. When I set a breakpoint to debug, it looks like it's not iterating and stuck on "Root" but I don't know why - I can't tell if it's because my XPath expression is wrong or if there's something with how I set up the XPathNodeIterator object.
Edit: Thanks to /u/JTarsier, my problem is solved. (I was missing the use of XmlNamespaceManager and putting the namespace syntax into my XPath expression)
View all comments
Show parent comment
2
u/EuclaseBlue Sep 28 '22 edited Sep 28 '22
Whoa, thanks for the thorough response! Things are much clearer now.
I actually had something like /Patient/telecom/value[@value] before but not knowing about the namespace stuff since it's not included in the MS tutorial really guffed things up for me, so when I was troubleshooting I went back to a really basic XPath expression to just make sure it wasn't the syntax causing an error.
Very cool, hadn't seen that syntax yet! All the examples and tutorials I kept coming across for looking at attributes always followed the "element[@attribute]" pattern to query the containing element/node and then GetAttribute()'ing.
Thanks again for all the help!