【问题标题】:XmlDocument returned by web service as XmlNode, then XPath doesn't work?Web 服务返回的 XmlDocument 作为 XmlNode,那么 XPath 不起作用?
【发布时间】:2013-09-11 15:50:55
【问题描述】:

我正在尝试使用接受 XmlDocument 并返回 XmlDocument 的 Web 服务/方法。当我将此 Web 服务的引用添加到我的 C# 应用程序时,代理代码被定义为使用 XmlNodes 而不是 XmlDocuments。这似乎是公认的行为(但确认和/或解释会很好 - 请参阅 SO here

但是,如果我获取返回的 XmlNode 对象并尝试对“SelectNodes(XPath)”进行简单的 XPath 查询,我找不到任何节点 - 但匹配的节点确实存在。

但是,如果我使用返回的 XmlNode 的 OuterXml,并从中创建一个新的 XmlDocument,我的 XPath 查询会找到我期望的节点。

这是为什么呢?返回的 XmlDocument/XmlNode (或之间的转换) 导致 XPath 查询无法按预期工作的原因是什么?

谢谢。

编辑: Xml 看起来像这样:

<Results xmlns="">
  <Result>
     :
    <Success>True</Success>
  </Result>
  <Result>
     :
    <Success>False</Success>
  </Result>
</Results>

...XPath 看起来像这样...

Dim xPath As String = "//Result[Success='False']"

If (xmlResults.SelectNodes(xPath).Count > 0) Then
    Throw New ApplicationException("Results returned indicate a problem:- " + xmlResults.OuterXml)
End If

【问题讨论】:

  • 您尝试的 XPath 看起来如何? XML 看起来如何?如果您有一个无父XmlNode,那么以/ 开头的路径可能与XmlDocument 的工作方式不同。或者,如果您有一个 XmlElement&lt;root&gt;&lt;foo&gt;bar&lt;/foo&gt;&lt;/root&gt; 返回,那么当然路径需要相对于 root 元素,因此您可以使用类似 root.SelectNodes("foo") 的路径来查找返回的所有 foo 子元素root 元素同时具有完整的 XmlDocument,您将使用 doc.SelectNodes("root/foo")doc.SelectNodes("/root/foo")

标签: web-services xpath


【解决方案1】:

创建我自己的 XmlDocument 的另一种方法是使用 Linq,如下所示:

Dim results As XDocument = XDocument.Parse(xmlResults.OuterXml)

If (results.Descendants("Success").Count(Function(node) node.Value.ToLower() = "false") > 0) Then
    Throw New ApplicationException("Results returned indicate a problem:- " + xmlResults.OuterXml)
End If

【讨论】:

    猜你喜欢
    • 2012-02-15
    • 2015-06-11
    • 2023-04-04
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 2013-06-13
    相关资源
    最近更新 更多