I have a collection of XML files with two possible root node values but with the same structure and child elements. I loop through each of the files and build an object r
of type Object
that I then add to a new objects
collection:
foreach (var file in files)
{
var r = from x in file.Descendants("RootNode")
select new Object
{
Field = ((string) x.Element("Field"))
};
objects.AddRange(r);
}
I want to do something like:
var r = from x in file.Descendants("RootNode") || file.Descendants("OtherRootNote")
but can't figure out a logical way of doing this other than having two loops. Is that the only way?
You can use Descendants()
to enumerate through all descendants, then add a standard where
clause to filter those with the desired names:
var r = from x in file.Descendants()
where x.Name == "RootNode" || x.Name == "OtherRootNode"
select new Object
{
Field = ((string)x.Element("Field"))
};
From the reference source, both overloads of Descendants()
just do a linear walk through the element tree, so doing the name check yourself isn't computationally more complex.