C#操作xml SelectNodes,SelectSingleNode总是返回NULL

SelectNodes,SelectSingleNode总是返回NULL

原文地址:http://www.cnblogs.com/linlf03/archive/2011/11/30/2268705.html

下面以一个简单的xml为例:

<?xml version="1.0"?> <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"> <error>Invalid Login</error> </message>

     下面尝试读取error节点的内容

XmlNode errorNode = xmldoc.SelectSingleNode("/message/error"); if (errorNode != null) Console.Writeline("There is an error");

     返回的结果一直为Null

     产生这个问题的原因就在于上面的xml文档中使用了命名空间,当xml中定义了命名空间时,在查找节点的时候需要使用下面的方法

XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmldoc.NameTable); nsMgr.AddNamespace("ns", "http://www.mydomain.com/MyDataFeed");
XmlNode errorNode = xmldoc.SelectSingleNode("/ns:message/ns:error", nsMgr);

    如果直接想定位到error,而不是从根开始,需要写为

xmldoc.SelectSingleNode("//ns:error", nsMgr); 

    感谢: http://stackoverflow.com/questions/1766254/selectsinglenode-always-returns-null

原文地址:https://www.cnblogs.com/KevinJasmine/p/4528679.html