Is there any way to to cut off some part of xDocument and still getting xDocument? By cutting off I mean keeping selected node.
I have XML like this:
<something 1>
<object>
Name="The only object I need"
<lev1>
<lev2>
Name= "Attribute I need"
</lev2>
<lev2>
Name= "Attribute I also need"
</lev2>
</lev1>
</object>
<object>
Name="Thing I want to remove"
<lev1>
<lev2>
Name= "useless attribute"
</lev2>
<lev2>
Name= "second useless atribute"
</lev2>
</lev1>
</object>
</something 1>
I need xDocument object containing only object with Name= "Attribute I need". I know it's easy, but I can't find it.
Edit:
I'm talking about a lot of really immense XML files. Therefore I can't just select something to remove.
You mean you want only the first child node? Yes, that's simple using the Remove
extension method:
doc.Root.Elements().Skip(1).Remove();
Sample:
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
var doc = new XDocument(new XElement ("root",
new XElement("child1", new XElement("grandchild1")),
new XElement("child2", new XElement("grandchild2"))));
Console.WriteLine("Document before:");
Console.WriteLine(doc);
doc.Root.Elements().Skip(1).Remove();
Console.WriteLine("Document after:");
Console.WriteLine(doc);
}
}
Output:
Document before:
<root>
<child1>
<grandchild1 />
</child1>
<child2>
<grandchild2 />
</child2>
</root>
Document after:
<root>
<child1>
<grandchild1 />
</child1>
</root>
To generalize this, you'd just want to change the Skip
call to select the elements you don't want to keep:
doc.Root
.Elements()
.Where(x => (string) x.Attribute("name") != "name to keep")
.Remove();
See more on this question at Stackoverflow