Reputation: 107
I'm trying to copy some xml node from a template to place them in another xml. The structure of the xml follows.
<grandparent>
<parent>
<children>
<grandchildren/>
</children>
<children>
<grandchildren/>
</children>
<children>
<grandchildren/>
</children>
</parent>
<parent>
<children>
<grandchildren/>
<grandchildren/>
<grandchildren/>
</children>
<children>
<grandchildren/>
<grandchildren/>
<grandchildren/>
</children>
<children>
<grandchildren/>
<grandchildren/>
<grandchildren/>
</children>
</parent>
</grandparent>
Is it possible for me to tranverse down the second parent and the selected children and grab all the grandchildren?And insert all the grandchildren into another xml file?
Upvotes: 1
Views: 891
Reputation: 8832
You can do it like this:
string input = @"<grandparent>
<parent>
<children>
<grandchildren/>
</children>
<children>
<grandchildren/>
</children>
<children>
<grandchildren/>
</children>
</parent>
<parent>
<children>
<grandchildren id=""1""/>
<grandchildren id=""2""/>
<grandchildren id=""3""/>
</children>
<children>
<grandchildren id=""4""/>
<grandchildren id=""5""/>
<grandchildren id=""6""/>
</children>
<children>
<grandchildren id=""7""/>
<grandchildren id=""8""/>
<grandchildren id=""9""/>
</children>
</parent>
</grandparent>";
XDocument doc = XDocument.Parse(input);
// Use XDocument.Load method to load XML content from file
//XDocument doc = XDocument.Load(<filepath>);
IEnumerable<XElement> elements = doc
.Root
.Elements("parent")
.ElementAt(1)
.Descendants("grandchildren");
XElement rootElement = new XElement("rootElement");
rootElement.Add(elements);
rootElement.Save(@"C:\Doc2.xml");
I presume that the XML you posted is not just a fragment but rather entire XML content you wish to parse.
The tricky part here is that you are accessing element by it's ordinal number, it should be done by some kind of ID attribute on parent
element, so it could be accessed by comparing it's ID instead of using ElementAt
method that retrieves the element according to it's ordinal position.
I added the id
attribute to grandchildren
so it would be visible that the grandchildren
elements belong to the second parent
element, not the first one.
Upvotes: 2
Reputation: 32787
XElement doc = XElement.Load("c:\\yourXML.xml");
XElement newdoc = new XElement("GrandChildren");
foreach (XElement x in doc.Descendants("parent").Skip(1).Descendants("children").Descendants("grandchildren"))
{
newdoc.Add(x);
}
newDoc now contains your required XML..
Upvotes: 0