Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 架构问题是否会阻止SelectNodes()查找节点?_C#_Xml_Xpath_Schema - Fatal编程技术网

C# 架构问题是否会阻止SelectNodes()查找节点?

C# 架构问题是否会阻止SelectNodes()查找节点?,c#,xml,xpath,schema,C#,Xml,Xpath,Schema,我有一些非常基本的XML: <ReconnectResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://platform.intuit.com/api/v1"> <ErrorMessage/> <ErrorCode>0</ErrorCod

我有一些非常基本的XML:

<ReconnectResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://platform.intuit.com/api/v1">    
    <ErrorMessage/>    
    <ErrorCode>0</ErrorCode>    
    <ServerTime>2012-01-04T19:21:21.0782072Z</ServerTime>    
    <OAuthToken>redacted</OAuthToken>    
    <OAuthTokenSecret>redacted</OAuthTokenSecret>
</ReconnectResponse>
我得到一个例外:

对象引用未设置为对象的实例

闻起来查找指定节点时出现问题。然而,考虑到XML是多么简单,我正在努力找出哪里出了问题

一时兴起,我将XML插入到。这会为每个元素类型提供XSD模式错误,如下所示:

找不到元素“”的架构信息


因此,我的问题是模式错误是否会导致
SelectSingleNode()
错过我的节点?第二个问题:如何修复它?

您忽略了元素的名称空间,在本例中是
http://platform.intuit.com/api/v1
。这是由根元素中的
xmlns=“…”
属性定义的,所有子元素都继承它

您需要使用前缀将此命名空间添加到命名空间管理器:

namespaceMan.AddNamespace("api", "http://platform.intuit.com/api/v1");
并在查询中使用此前缀:

xmlDoc.SelectSingleNode(@"/api:ReconnectResponse/api:ErrorCode", namespaceMan).InnerText;
另一方面,LINQtoXML是比
XmlDocument
干净得多的API,并且提供了比XPath更好的查询语言。此代码将获取整数形式的错误代码:

var doc = XDocument.Parse(xmlString);

XNamespace api = "http://platform.intuit.com/api/v1";

var errorCode = (int) doc.Descendants(api + "ErrorCode").Single();

不知道为什么我没有发现LINQ到XML——显然是一条路要走!
var doc = XDocument.Parse(xmlString);

XNamespace api = "http://platform.intuit.com/api/v1";

var errorCode = (int) doc.Descendants(api + "ErrorCode").Single();