Mike
Mike

Reputation: 1261

Linq query based on attribute

Ran into another challenge. I looked through some of the questions that I found here, but I can't seem to piece together what I need.

OK I have a XML file:

<Output id="1">
    <path rename="Off" name="pattern-1">d:\temp</path>
  </Output>

  <Output id="2">
      <path isRename="False" name="pattern-1" >d:\temp\out2</path>
      <path isRename="True"  name="pattern-1" >d:\temp\out3</path>
      <path isRename="False" name="pattern-1">d:\temp\out4</path>
  </Output>

What I need to do is find the <Output> tag based on the id attribute . Then I need to loop through all of the <path> tags and get the attribute and path value. I tried a few thing based on a previous question I had asked but I couldn't get it to work

var results = from c in rootElement.Elements("Output") 
              where (string)c.Attribute("Id") == "2" select c;

foreach (var path in rootElement.Elements("Output").Elements("path"))
{
    string p  = path.Value;
}

Upvotes: 4

Views: 212

Answers (2)

Dmitrii Lobanov
Dmitrii Lobanov

Reputation: 4977

I would recommend using some XPath to select nodes you need:

foreach (XElement path in root.XPathSelectElements("/Output/path[../@id=1]"))
{
    string value = path.Value;
}

Indeed, sometimes XPath lets you write more readable and maintanable code. You just use some expression that replaces several linq-to-xml statements.

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

Your first line doesn't do anything if you don't actually use the results.

foreach (var outputElement in rootElement.Elements("Output")
                                         .Where(e => (string)e.Attribute("id") == "1"))
{
    foreach (var pathElement in outputElement.Elements("path"))
    {
        // ...
    }
}

If your id attribute is guaranteed to be unique (which it should), you can get rid of the first foreach and just get the individual <Output> directly:

var outputElement = rootElement.Elements("Output")
                               .FirstOrDefault(e => (string)e.Attribute("id") == "1"));

Upvotes: 1

Related Questions