SelectSingleNode always returns null?

♀尐吖头ヾ 提交于 2019-12-05 17:42:48

问题


Taking this simplifed example of my 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>

I am trying to select the 'error' node using SelectSingleNode method, however using the following code it always returns NULL?

XmlNode errorNode = oss.SelectSingleNode("/message/error");
if (errorNode != null)
     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?


回答1:


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:

XmlNamespaceManager nsMgr = new XmlNamespaceManager(oss.NameTable);
nsMgr.AddNamespace("ns", "http://www.mydomain.com/MyDataFeed");

XmlNode errorNode = oss.SelectSingleNode("/ns:message/ns:error", nsMgr);

Marc



来源:https://stackoverflow.com/questions/1766254/selectsinglenode-always-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!