1

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

More copy&paste errors than grammar, but thanks for editing ;D
I just had to correct the "Your", it gave me the creeps. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.