Select more than one node from XML using LINQ

I have such XML

<root> <content> .... </content> <index> .... </index> <keywords> .... </keywords> </root> 

But I need to choose just and nodes.

 <content> .... </content> <index> .... </index> 

I learned how to select only one node.

 XElement Content = new XElement("content", from el in xml.Elements() select el.Element("content").Elements()); 

How can I get both nodes?

+4
source share
3 answers
 var elements = from element in xml.Root.Elements() where element.Name == "content" || element.Name == "index" select element; var newContentNode = new XElement("content", elements); 
+6
source

After loading the xml file, you can get all content nodes through:

 var cons = from con in xmlFile.Descendants("content"); 

and similarly you can get index nodes like:

 var idxs = from idx in xmlFile.Descendants("index") 

I do not think you can query two nodes using one query string.

+1
source

Using lambda:

  var elements = document .Descendants() .Where(element => element.Name == "content" || element.Name == "index"); 
+1
source

Source: https://habr.com/ru/post/1309516/


All Articles