C# 架构问题是否会阻止SelectNodes()查找节点?
我有一些非常基本的XML: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
<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();