Is it possible to ignore namespaces in c# when using xPath?
Asked Answered
A

1

23

I could be given either of the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<dc:video xmlns:dc="http://purl.org/dc/elements/1.1/">
  <dc:title>
    A vid with Pete
  </dc:title>
  <dc:description>
  Petes vid
  </dc:description>
  <dc:contributor>
    Pete
  </dc:contributor>
  <dc:subject>
    Cat 2
  </dc:subject>
</dc:video>

Or:

<?xml version="1.0" encoding="UTF-8"?>
<video>
  <title>
    A vid with Pete
  <title>
  <description>
  Petes vid
  <description>
  <contributor>
    Pete
  <contributor>
  <subject>
    Cat 2
  <subject>
</video>

Im trying to access an element:

string title = xmlDocFromOneLan.SelectSingleNode(@"/video/title").InnerXml;

But with xml document 1 it doesnt work due to the namespace.

Is there a way in c# to ignore the namespace using xpath? I simply want to select the node I really dont care about the namespace. (the namespace could be DC DN or DCN etc).

"/video"

would read:

<video></video>
or
<dc:video></video>
or
<dcn:video></video>
Aircrew answered 30/11, 2010 at 12:5 Comment(1)
You could use Namespace = false on a XmlTextReader see: https://mcmap.net/q/166001/-how-to-ignore-namespaces-with-xpathSummer
P
48

With XPath 1.0 all you can do is /*[local-name() = 'video']/*[local-name() = 'title']. With XPath 2.0 you can use a wildcard /*:video/*:title.

Papua answered 30/11, 2010 at 12:24 Comment(2)
Thanks Martin, do you know where I can get documentation relating to that?Aircrew
Pete, XPath 1.0 and 2.0 are W3C specifications you can find online: w3.org/TR/xpath, w3.org/TR/xpath20. Microsoft only supports XPath 1.0, they do have documentation on that on MSDN: msdn.microsoft.com/en-us/library/ms256115.aspx. XPath 2.0 is implemented by third parties like XQSharp xqsharp.com or Saxon 9 saxon.sourceforge.net. Saxon also has a good documentation, the *:foo syntax is documented at saxonica.com/documentation/expressions/axissteps.xml.Papua

© 2022 - 2024 — McMap. All rights reserved.