无法让XPath与未命名的命名空间一起使用

时间:2012-12-10 19:11:54

标签: c# .net xml xpath

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

2 个答案:

答案 0 :(得分:0)

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;

可以帮到你?

答案 1 :(得分:0)

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

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

库处理为您执行命名空间。