开发者

c# can't read element attribute with xpath

开发者 https://www.devze.com 2023-01-09 00:22 出处:网络
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

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

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]");

which returns blank

This is the xml i am trying to read:

<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...


is this the full 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]"); 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


You're trying to read all Light-elements with a Name-attribute.

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.

Remember, [] is for conditions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号