0

How to read an XPathDocument that has a namespace

 2 years ago
source link: https://www.codesd.com/item/how-to-read-an-xpathdocument-that-has-a-namespace.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to read an XPathDocument that has a namespace

advertisements

I have the following example XML file:

<Top xmlns="abbr:SomeNSValue">
  <Next>
    <Other>SomeValue</Other>
  </Next>
</Top>

I load it up and try to read it like this:

FileStream stream = new FileStream(@".\TestXML.xml", FileMode.Open);
XPathDocument xPathDocument = new XPathDocument(stream);
XPathNavigator navigator = xPathDocument.CreateNavigator();

XmlNamespaceManager ns = null;
if (navigator.NameTable != null)
{
    ns = new XmlNamespaceManager(navigator.NameTable);
    ns.AddNamespace("abbr", "SomeNSValue");
}

XPathNodeIterator iterator = navigator.Select("/Top/Next", ns);
iterator.MoveNext();

Console.WriteLine(iterator.Current.InnerXml);

This outputs the Full XML shown above. Not what I am looking for (I want to select the contents of the "Next" node.

But if I take the xmlns="abbr:SomeNSValue out of the XML and try again then I get what I was looking for:

<Other>SomeValue</Other>

In my real scenario I have the XML fed to me and I would rather not have to modify it to take the Namespace off.

Is there a way I can make this work with the namespace in it?

Note: Incase it matters this is the actual namespace that I have in my XML file: xmlns="urn:hl7-org:v2xml"


Your namespace declaration is wrong:

<Top xmlns:abbr="SomeNSValue">
  <Next>
    <Other>SomeValue</Other>
  </Next>
</Top>

When you do this magical change the rest of your code works :)..


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK