How to find nodes entirely between two specified nodes
In a XML document such as the following:
<root>
<fish value="Start"/>
<pointlessContainer>
<anotherNode value="Pick me!"/>
<anotherNode value="Pick me too!"/>
<fish value="End"/>
</pointlessContainer>
</root>
How can I use the wonder of LINQ to XML to find any nodes completely contained by the fish
nodes? Note that in this example, I have deliberately placed the fish
nodes at different levels in the document, as I anticipat开发者_如何学编程e this scenario will occur in the wild.
Obviously, in this example, I would be looking to get the two anotherNode
nodes, but not the pointlessContainer
node.
NB: the two 'delimiting' nodes may have the same type (e.g. fish
) as other non-delimiting nodes in the document, but they would have unique attributes and therefore be easy to identify.
For your sample, the following should do
XDocument doc = XDocument.Load(@"..\..\XMLFile2.xml");
XElement start = doc.Descendants("fish").First(f => f.Attribute("value").Value == "Start");
XElement end = doc.Descendants("fish").First(f => f.Attribute("value").Value == "End");
foreach (XElement el in
doc
.Descendants()
.Where(d =>
XNode.CompareDocumentOrder(d, end) == -1
&& XNode.CompareDocumentOrder(d, start) == 1
&& !end.Ancestors().Contains(d)))
{
Console.WriteLine(el);
}
But I haven't tested or thoroughly pondered whether it works for other cases. Maybe you can check for some of your sample data and report back whether it works.
精彩评论