Reputation: 37909
<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
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
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
Reputation: 14477
Use this:
var grid = XElement.Parse(@"<Grid>
<StringColumn Header=""Name""/>
<DateColumn Header=""Date""/>
</Grid>");
var elements = grid.XPathSelectElements(".//*[@Header]");
Upvotes: 0
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