score:1

Accepted answer

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

score:0

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.


Related Articles