简体   繁体   中英

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?

This should give you the required elements:

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

Something like this should work:

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

Use this:

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

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

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

        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM