【发布时间】:2021-07-05 16:56:18
【问题描述】:
我有xml作为响应,需要找到标记的红色箭头节点:
我的代码:
//response to xmlDocument
document = new XmlDocument();
document.LoadXml(response.Content);
XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable);
foreach (XmlAttribute curAttribute in document.DocumentElement.Attributes)
{
if (curAttribute.Prefix.Equals("xmlns"))
{ ns.AddNamespace(curAttribute.LocalName, curAttribute.Value); }
}
string xpath = "//edmx:Edmx/edmx:DataServices/Schema[@Namespace='Core.Entities']/EntityType[@Name='Office']/Property[@Name='OfficeKeyNumeric']";
XmlNode node = document.SelectSingleNode(xpath, ns);
}
我有一个错误,给定的 XPath 找不到节点,节点为空。
我尝试了什么:
and
string xpath = "//edmx:Edmx/edmx:DataServices/Schema[@Namespace='Core.Entities' and @xmlns='http://docs.oasis-open.org/odata/ns/edm']/EntityType[@Name='Office']/Property[@Name='OfficeKeyNumeric']";
没有and
string xpath = "//edmx:Edmx/edmx:DataServices/Schema[@Namespace='Core.Entities'][@xmlns='http://docs.oasis-open.org/odata/ns/edm']/EntityType[@Name='Office']/Property[@Name='OfficeKeyNumeric']";
也尝试使用管道 |、& - 没有任何帮助。
为什么它不起作用,是否有可能让它以这种方式起作用?
我现在使用的唯一一个可行的解决方案是在加载之前从 XML 文档中删除 xmlns="http://docs.oasis-open.org/odata/ns/edm",之后我上面的代码就可以正常工作了。
document.LoadXml(response.Content.Replace("xmlns=\"http://docs.oasis-open.org/odata/ns/edm\"", ""));
【问题讨论】:
-
您是否注意到
Schema元素也有自己的xmlns属性? -
相当于
<edm:Schema xmlns:edm="http://docs.oasis-open.org/odata/ns/edm">。这么想吧。 -
是的,这是一个问题——如何在它下面找到一个节点?我目前正在从文档中删除该 xmlns 和相关链接,因为如果 Shema 有两个属性,则无法到达节点
-
谢谢@madreflection 会试试的
标签: c# xmldocument xmlnode