如何解决无法通过具有两个属性的 Xpath 选择 XmlNode
我的代码:
//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
元素及其后代在 http://docs.oasis-open.org/odata/ns/edm
命名空间中声明,必须在
xpath
您正在寻找的语句。
string xpath = "//edmx:Edmx/edmx:DataServices/edm:Schema[@Namespace='Core.Entities']/edm:EntityType[@Name='Office']/edm:Property[@Name='OfficeKeyNumeric']";
确保使用这些命名空间初始化您的 XmlNamespaceManager
。
XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable);
ns.AddNamespace("edmx","http://docs.oasis-open.org/odata/ns/edmx");
ns.AddNamespace("edm","http://docs.oasis-open.org/odata/ns/edm");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。