I ran into a similar problem with the default empty namespace. In this XML example, I have a combination of elements with namespace prefixes and one element (DataBlock) without:
<src:SRCExample xmlns="urn:some:stuff:here" xmlns:src="www.test.com/src" xmlns:a="www.test.com/a" xmlns:b="www.test.com/b"> <DataBlock> <a:DocID> <a:IdID>7</a:IdID> </a:DocID> <b:Supplimental> <b:Data1>Value</b:Data1> <b:Data2/> <b:Extra1> <b:More1>Value</b:More1> </b:Extra1> </b:Supplimental> </DataBlock> </src:SRCExample>
I tried using XPath, which worked in XPath Visualizer, but did not work in my code:
XmlDocument doc = new XmlDocument(); doc.Load( textBox1.Text ); XPathNavigator nav = doc.DocumentElement.CreateNavigator(); XmlNamespaceManager nsman = new XmlNamespaceManager( nav.NameTable ); foreach ( KeyValuePair<string, string> nskvp in nav.GetNamespacesInScope( XmlNamespaceScope.All ) ) { nsman.AddNamespace( nskvp.Key, nskvp.Value ); } XPathNodeIterator nodes; XPathExpression failingexpr = XPathExpression.Compile( "/src:SRCExample/DataBlock/a:DocID/a:IdID" ); failingexpr.SetContext( nsman ); nodes = nav.Select( failingexpr ); while ( nodes.MoveNext() ) { string testvalue = nodes.Current.Value; }
I narrowed it down to the XPath “DataBlock” element, but couldn't get it working, except for a simple substitution of the DataBlock element:
XPathExpression workingexpr = XPathExpression.Compile( "/src:SRCExample/*/a:DocID/a:IdID" ); failingexpr.SetContext( nsman ); nodes = nav.Select( failingexpr ); while ( nodes.MoveNext() ) { string testvalue = nodes.Current.Value; }
After scrambling and googling multiple times (which landed on me here), I decided to tackle the default namespace directly in my XmlNamespaceManager, changing it to:
foreach ( KeyValuePair<string, string> nskvp in nav.GetNamespacesInScope( XmlNamespaceScope.All ) ) { nsman.AddNamespace( nskvp.Key, nskvp.Value ); if ( nskvp.Key == "" ) { nsman.AddNamespace( "default", nskvp.Value ); } }
So now "default" and "point to the same namespace. Once I have done that, XPath" / src: SRCExample / default: DataBlock / a: DocID / a: IDID "returned my results as I wanted Hope this helps clarify the issue for others.
Brandon Sep 27 '11 at 19:50 2011-09-27 19:50
source share