我有这种xml
<soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/.">
<soap-env:body>
<SomeElement xmlns='http://www.MySite.com/SOAP' />
</soap-env:body>
</soap-env:envelope>
我正在尝试使用xpath获取'SomeElement'节点,就像这样
var xDocument = XDocument.Parse(strXml);
var xmlNamespace = new XmlNamespaceManager(xDocument.CreateReader().NameTable);
xmlNamespace.AddNamespace("soap-env", "http://schemas.xmlsoap.org/soap/envelope/.");
xmlNamespace.AddNamespace("", "http://www.MySite.com/SOAP");
var xmlBody = xDocument.XPathSelectElements("soap-env:envelope/soap-env:body/SomeElement", xmlNamespace);
并在xmlBody
中返回null,但如果删除xmlns='http://www.MySite.com/SOAP'
命名空间,一切正常。
答案 0 :(得分:1)
如果您在默认命名空间前加上我会认为它应该有用,所以请更改:
xmlNamespace.AddNamespace("", "http://www.MySite.com/SOAP");
var xmlBody = xDocument.XPathSelectElements("soap-env:envelope/soap-env:body/SomeElement", xmlNamespace);
要:
xmlNamespace.AddNamespace("pref", "http://www.MySite.com/SOAP");
var xmlBody = xDocument.XPathSelectElements("soap-env:envelope/soap-env:body/pref:SomeElement", xmlNamespace);