【问题标题】:Cannot get XPath to work with unnamed namespace无法让 XPath 使用未命名的命名空间
【发布时间】:2012-12-10 19:11:53
【问题描述】:

XML(片段):

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetXMLResponse xmlns="http://sitecore.net/visual/">
<GetXMLResult>
<sitecore xmlns="">
<status>ok</status>

代码(片段):

XmlNamespaceManager nsManager = new XmlNamespaceManager(template.NameTable);
nsManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsManager.PushScope();

XmlNode sitecoreRoot = template.SelectSingleNode("/soap:Envelope/soap:Body/*[namespace-uri()='http://sitecore.net/visual/' and local-name()='GetXMLResponse']", nsManager);

string status = sitecoreRoot.SelectSingleNode("/GetXMLResult/sitecore/status").Value;

sitecoreRoot 元素返回正确的节点。然而,获取状态的 XPath 始终返回 null,即使 siteCoreRoot.OuterXMl 属性显示该元素存在。

我唯一能想到的就是这行:

<sitecore xmlns="">

正在抛弃 XPath

TIA

【问题讨论】:

    标签: c# .net xml xpath


    【解决方案1】:
    XmlNamespaceManager ns = new XmlNamespaceManager(cd.NameTable);
            ns.AddNamespace("sp", "http://schemas.xmlsoap.org/soap/envelope/");
            ns.AddNamespace("sc", "http://sitecore.net/visual/");
            XmlNode sitecoreRoot = cd.SelectSingleNode("//sp:Envelope/sp:Body/sc:GetXMLResponse/sc:GetXMLResult/sitecore/status", ns);
    var status = sitecoreRoot.InnerText;
    

    可以帮到你吗?

    【讨论】:

    • 我之前实际上已经尝试过该解决方案,但没有运气。但是,您的回答确实促使我回答自己的问题。 “gotcha”是节点:。似乎空的 xmlns 属性“关闭”了命名空间。所以工作的 XPath 看起来像:/soap:Envelope/soap:Body/ns:GetXMLResponse/ns:GetXMLResult/sitecore/status
    【解决方案2】:

    如果你只想要状态节点,你可以试试this xml library和下面的XPath。

    XElement root = XElement.Load(file); // or .Parse(string)
    XElement status = root.XPathElement("//status");
    

    库为您处理命名空间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多