OK, so I’ve been pulling my hair out all day with this problem in XPATH and C#.
I have the following XML document:
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0" xmlns:c="http://base.google.com/cns/1.0">
<item id="362">
<title>Family Holiday</title>
<description>a long, wordy description goes here</description>
<g:id xmlns:g="g">FPS</g:id>
<g:latitude xmlns:g="g">42.502260</g:latitude>
<g:longitude xmlns:g="g">1.532850</g:longitude>
</item>
</entry>
I then do the following:
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(xmlfile);
XmlNamespaceManager _nameSpaceManager = new XmlNamespaceManager(_xmlDocument.NameTable);
_nameSpaceManager.AddNamespace("RN", "http://www.w3.org/2005/Atom");
_nameSpaceManager.AddNamespace("g", "http://base.google.com/ns/1.0");
_nameSpaceManager.AddNamespace("c", "http://base.google.com/cns/1.0");
XPathNavigator navigator = _xmlDocument.CreateNavigator();
My problem lies with this:
XmlNode nde = _xmlDocument.SelectSingleNode("/RN:entry/RN:item/g:id", _nameSpaceManager);
returns null – not the Id node. However,
XmlNode nde = _xmlDocument.SelectSingleNode("/RN:entry/RN:item/RN:title", _nameSpaceManager);
does return the title node.
Any ideas on what I’m doing wrong would be much appreciated!
Cheers
Simon
Your local namespace declarations are overriding the root namespace definitions;
Is effectively saying the g:id attribute here is coming from the namespace ‘g’ not the same namespace as g is defined as coming from in your document element.
For example, if I change your XML to:
or simply:
Your XPath expression works as the local namespace for
gnow matches the document element namespace declaration ofgIf you are stuck with your XML then the only other thing you can do is:
Your XPath will now work.
Tested with XmlDocument, .Net Framework version 4.