简体   繁体   English

c#无法使用xpath读取element属性

[英]c# can't read element attribute with xpath

This code can't read a specific attribute - the name attribute more specifically. 这段代码无法读取特定的属性-更具体地说,名称属性。 Instead it read the text of node elements and does a concat on them - result: 1F20 is added to the list 相反,它读取节点元素的文本并对它们进行合并-结果:1F20被添加到列表中

var reader = new StringReader(xml);
            var xmlreader = new XmlTextReader(reader);
            xmlreader.WhitespaceHandling = WhitespaceHandling.None;
            var doc = new XPathDocument(xmlreader);
            var nav = doc.CreateNavigator();
            XPathExpression expr = nav.Compile("/Area/Lights/Light[@Name]");
            XPathNodeIterator iterator = nav.Select(expr);

            var list = new List<string>();
            while (iterator.MoveNext())
            {
                XPathNavigator nav2 = iterator.Current.Clone();
                list.Add(nav2.Value);  
            }

I have also tried: XPathExpression expr = nav.Compile("//Light[@Name]"); 我也尝试过:XPathExpression expr = nav.Compile(“ // Light [@Name]”);

which returns blank 返回空白

This is the xml i am trying to read: 这是我要阅读的xml:

<Light Index="1" SetChannel="72" GetChannel="60" Name="y1 d1">
      <Nodes>1F</Nodes>
      <Nodes>20</Nodes>
    </Light>

What i am doing wrong - first attempt at xpath... 我做错了-第一次尝试xpath ...

is this the full XML? 这是完整的XML吗? using your snippet here this works 在这里使用您的代码片段

XPathExpression expr = nav.Compile("Light/@Name");

just to add the usage of XPathExpression expr = nav.Compile("/Area/Lights/Light[@Name]"); 只是添加XPathExpression expr = nav.Compile("/Area/Lights/Light[@Name]");的用法XPathExpression expr = nav.Compile("/Area/Lights/Light[@Name]"); is a filter, you are asking for a Light node that has an attribute called Name, or you may do something like @Name = 'bob' where you ask for a Light node with an attribute of Name equal to Bob 是一个过滤器,您正在请求一个名为Name的属性的Light节点,或者可以执行类似@Name = 'bob' ,在其中您请求一个Name属性等于Bob的Light节点

You're trying to read all Light -elements with a Name -attribute. 您正在尝试读取具有Name属性的所有Light -elements。

Try //Light[@Name='xyz']/@Name in order to read the Name -attribute from the Light -element where Name='xyz' or //Light/@Name for all Name -attributes. 尝试//Light[@Name='xyz']/@Name以便从Light -e元素读取Name属性,其中Name='xyz'//Light/@Name代表所有Name属性。

Remember, [] is for conditions. 请记住, []是用于条件的。

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

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