Greg Gum
Greg Gum

Reputation: 37909

How to get all descendants with a particular attribute - Linq to Xml

<Grid>
   <StringColumn Header="Name"/>
   <DateColumn Header="Date"/>
</Grid>

There is probably an existing answer to this question, but I cannot seem to find it.

I need to find all xml elements which have an attribute of "Header"

The name of the element can be different.

How do I do that with Linq to XML?

Upvotes: 1

Views: 6783

Answers (4)

jdweng
jdweng

Reputation: 34419

Using xml linq. Code is prints any Grid elements that have children with Header attributes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication7
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> headers = doc.Descendants("Grid").Where(x => x.Elements().Where(y => y.Attribute("Header") != null).Any()).ToList();

        }
    }

}

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

This should give you the required elements:

XDocument document = ...;
var elementsWithHeader = document.Descendants()
                                 .Where(e => e.Attributes().Any(a => a.Name == "Header"));

Upvotes: 3

Xiaoy312
Xiaoy312

Reputation: 14477

Use this:

var grid = XElement.Parse(@"<Grid>
   <StringColumn Header=""Name""/>
   <DateColumn Header=""Date""/>
</Grid>");

var elements = grid.XPathSelectElements(".//*[@Header]");

Upvotes: 0

Nate Jenson
Nate Jenson

Reputation: 2794

Something like this should work:

IEnumerable<XElement> elements =  
    from el in root.Elements("Grid")  
    where (string) el.Attribute("Header") != null  
    select el; 

Upvotes: 0

Related Questions