I have an excel vba application which outputs some data as XML. I need to read this xml data in a .NET application. The file automatically contains several namespaces which I can't prevent. Here is the XML file (similified):
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'>
Usually there are loads of z:row elements, it is these that I need to get. The code I have written uses XPath to get to them, but is complicated by namespaces, and at the moment returns no rows at all. I load an XmlDocument called xmlDoc, and then my code is:
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsMgr.AddNamespace("", xmlDoc.DocumentElement.NamespaceURI);
nsMgr.AddNamespace("s", xmlDoc.DocumentElement.NamespaceURI);
nsMgr.AddNamespace("dt", xmlDoc.DocumentElement.NamespaceURI);
nsMgr.AddNamespace("rs", xmlDoc.DocumentElement.NamespaceURI);
nsMgr.AddNamespace("z", xmlDoc.DocumentElement.NamespaceURI);
XmlElement root = xmlDoc.DocumentElement;
XmlNodeList nodes = root.SelectNodes(@"/xml/rs:data/z:row",nsMgr);
Whilst this doesn't generate an error, it also doesn't return any rows. Anyone know what I am doing wrong?
Thanks in advance!
RichPosted Jul 30, 2010, 5:10 PM
Thankyou for your reply. Yes I have read serveral relevant articles, however I still could not quite identify what I was doing wrong. However after some more experimentation I realised I need to include the exact urn or uuid values from the xml file rather than using xmlDoc.DocumentElement.NamespaceURI. Also the XmlElement root object wasn't necessary, but didn't affect anything.
So, in case this helps any other users (after all that is what we are trying to do here isn't it?) the corrected code is as follows:
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsMgr.AddNamespace("s", "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882");
nsMgr.AddNamespace("dt", "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882");
nsMgr.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
nsMgr.AddNamespace("z", "#RowsetSchema");
XmlNodeList nodes = xmlDoc.SelectNodes(@"/xml/rs:data/z:row",nsMgr);
I hope thats of some use to someone!
Cheers,
Rich
Sam HobbsPosted Jul 30, 2010, 2:25 PM
RichPosted Jul 30, 2010, 10:16 AM