Q:
Taking this simplifed example of my XML:
1 <?xml version="1.0"?> 2 <message xmlns="http://www.mydomain.com/MyDataFeed" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mydomain.com/MyDataFeed https://secure.mydomain/MyDataFeed/myDataFeed.xsd" requestId="13898" status="1"> 3 <error>Invalid Login</error> 4 </message>
I am trying to select the 'error' node using SelectSingleNode method, however using the following code it always returns NULL?
1 XmlNode errorNode = oss.SelectSingleNode("/message/error"); 2 if (errorNode != null) 3 Console.Writeline("There is an error");
From research I have done this is related to namespaces but I simply can't get anything to work. Any advice?
A:
You're missing the XML namespace defined by the <message>
node in your SelectSingleNode
call. Assuming oss
is an XmlDocument
instance, you need to do this:
1 XmlNamespaceManager nsMgr = new XmlNamespaceManager(oss.NameTable); 2 nsMgr.AddNamespace("ns", "http://www.mydomain.com/MyDataFeed"); 3 XmlNode errorNode = oss.SelectSingleNode("/ns:message/ns:error", nsMgr);
转载自:http://stackoverflow.com/questions/1766254/selectsinglenode-always-returns-null