1

I try to evaluate simple xpath

"//pr:Name"

for this xml

<?xml version="1.0" encoding="utf-8"?>
<pr:Products xmlns:pr="http://www.example.com/">
    <pr:Name>Coffee</pr:Name>
</pr:Products>

but I get xml file in run-time i.e. I can't fill XmlNamespaceManager using method AddNamespace() (this why evaluating failed). I tried to do this trick

    XDocument xdoc;
    XmlReader reader;
    using (var stream = new FileStream("test.xml", FileMode.Open))
    {
        reader = new XmlTextReader(stream);
        xdoc = XDocument.Load(reader);
    }
    var nsManager = new XmlNamespaceManager(reader.NameTable);
    var xpath = "//pr:Name";
    var xvalue = xdoc.XPathEvaluate(xpath, nsManager);

but it does not help me. Do you have any idea how to resolve namespaces for XPath or evaluate XPath in other way? Thank you!

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • You can possibly find your answer at https://stackoverflow.com/questions/14920082/xml-reading-child-nodes or https://stackoverflow.com/questions/15903671/how-can-i-access-a-single-xml-elements-value-using-c-net-web-pages-with-webmat – Usama Oct 28 '18 at 11:01
  • @Usama, you suggest use XmlDocument instead of XDocument? But how it help me to resolve namespaces? – Dmitry Semin Oct 28 '18 at 11:22
  • 1
    **Try this** https://stackoverflow.com/questions/40796231/how-does-xpath-deal-with-xml-namespaces – Usama Oct 28 '18 at 12:37
  • https://stackoverflow.com/questions/5239685/xml-namespace-breaking-my-xpath – Usama Oct 28 '18 at 12:38
  • Usama, I should not defeat namespaces. It is not my case – Dmitry Semin Oct 28 '18 at 15:14
  • This might help https://stackoverflow.com/questions/308926/verify-an-xpath-in-net – Usama Oct 28 '18 at 16:36

1 Answers1

1

If you don't know namespace at compile time, you might probably use this XPath:

//*[local-name() = 'Name']

This XPath selects all Name elements.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125