简体   繁体   English

Xpath 无法使用具有两个属性的 select XmlNode

[英]Unable select XmlNode by Xpath with two attributes

I have xml as a response, need to find marked red arrow node:我有 xml 作为响应,需要找到标记的红色箭头节点:

在此处输入图像描述

My code:我的代码:

 //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);
        }

I have an error that node can't be found by given XPath, node is null.我有一个错误,给出的 XPath 找不到节点,节点是 null。

What I tried:我尝试了什么:

with and 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']";
        

without and没有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']";

Tried also with pipe |也试过 pipe | , & - nothing helped. , & - 没有任何帮助。

Why it doesn't work and is it possible to make it work in that way?为什么它不起作用,是否有可能让它以这种方式工作?

The only one working solution I'm using now is to remove xmlns="http://docs.oasis-open.org/odata/ns/edm" from XML document before loading, after that my code above works fine.我现在使用的唯一一个可行的解决方案是在加载之前从 XML 文档中删除xmlns="http://docs.oasis-open.org/odata/ns/edm" ,之后我上面的代码可以正常工作。

document.LoadXml(response.Content.Replace("xmlns=\"http://docs.oasis-open.org/odata/ns/edm\"", ""));

The Schema element and its descendants are declared in the http://docs.oasis-open.org/odata/ns/edm namespace, which must be referenced in the xpath statement you are looking for. 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']";

Make sure to have your XmlNamespaceManager initialized with these namespaces.确保使用这些命名空间初始化您的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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM