I have just been trying to load an XML document into a .NET XMLDocument and then use the SelectNodes method passing an XPath string to get a XMLNodeList in return. Easy so I thought! The XML being loaded did have a default namespace, and as such all the elements within it did not have any namespace references... and equally therefore I assumed that my XPath query would not need any namespace prefix especially since the XML loaded had none. Alas, my code didn't work!
The solution, and of course easy when you know how, is to use an XMLNamespaceManager object and add a reference to your default namespace (or any other namespaces used within your document) but the key thing is to add a prefix - it does not matter than the source XML isn't using prefixes. My initial thought was to just add the namespace again without a prefix - nope, this doesn't work! No, once you add the namespace with prefix, and then pass the namespace manager object as a parameter in your SelectNodes call plus your newly prefixed xpath query and you will find delightedly you have some result nodes!!
An example...
//So key to note that the lcw namespace is the default namespace in my XML file it has no prefix in the file - but here it not associated with the prefix lcw
xmlSupplierMap = new XmlDocument();
namespaceMan = new XmlNamespaceManager(xmlSupplierMap.NameTable);
namespaceMan.AddNamespace("lcw", http://www.defaultnamespace.domain/blah);
xmlSupplierMap.Load("filename of xml.xml");
//My new XPath query uses the prefix assigned previously lcw: and bingo we get data!
XmlNodeList worksheetNodelist = xmlSupplierMap.SelectNodes("lcw:worksheet", namespaceMan);
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment