0

I want to select xml node based on attribute. I'm very new to how linq to xml works, and can't write proper query. How can I fix it?

My XML

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Enable0" value="true" />
    <!-- dumb comment -->
    <add key="Enable1" value="false" />
    <!-- dumb comment1-->
    <add key="Enable2" value="true" />
    <add key="Enable3" value="false" />
    <!-- dumb comment2 -->
    <add key="Enable4" value="true" />
  </appSettings>
  <asdf>
    <a key="b"></a>
    <a key="c"></a>
    <a key="d"></a>
  </asdf>
</configuration>

My attempt:

        private string GetAttribute(string name)
    { 

        //???
        var query = from node in deafultElement.Elements("add")
                    where node.Attribute("key").Value == name
                    select node.Attribute("value").value;

        return query.toString();
        //currently returns "System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]"
    }
4
  • @mjwills I'll edit and add some sample xml I use for tests, but what more code do you want? I'm not sure which parts of code would be relevant for this question. Commented Feb 22, 2018 at 12:20
  • You do a select .Value which will be a string, not a Node/Element. Commented Feb 22, 2018 at 12:23
  • @mjwills then I can simply delete all code and show only that broken query. Would that be good option? Commented Feb 22, 2018 at 12:23
  • Don't use Value : (string)node.Attribute("key") & (string)node.Attribute("value") If the object doesn't exist you will get an error. Commented Feb 22, 2018 at 12:24

2 Answers 2

2

You can also use linq methods' syntax to reach the same result.

string value = defaultElement.Elements("add")
            .FirstOrDefault(n => n.Attribute("key").Value == name)
            .Attribute("value").Value;
Sign up to request clarification or add additional context in comments.

Comments

0
  var query = (from node in deafultElement.Elements("add")
      where node.Attribute("key").Value == name
      select node.Attribute("value").Value).FirstOrDefault();
  return query

Comments

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.