abhi
abhi

Reputation: 3136

Merging XML Elements with LINQ

I have two XML documents. My objective is to replace one of the nodes in the first document with the entire contents of the second Xml documents. So the first document - Parent looks something like this:

<Root>
    <AgencyName = "Some Agency"/>
    <Originator = "Some other Agency"/>
    <Type = "AnonymousType"/>
    <Details/>
</Root>

The second document - children looks like this:

<Root>
    <Details>
        <Detail1>
            ...
        </Detail1>
        <Detail2>
            ...
        </Detail2>
        <Detail3>
            ...
        </Detail3>
    </Details>
</Root>

The node <Details/> has to be replaced with the contents of the second document. I am attempting to use Linq to XML to do this. The first document is represented in an XDocument class and the second one is represented in an XElement class. There are several child attributes for <Detail/> and I haven't listed them here.

I am attempting to replace the element from the first document with this XElement class. If I try something like this,

ParentDoc.Element("Details").ReplaceAll(children);

it is unlikely to work. How should I do the replace?

Upvotes: 0

Views: 1326

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

var doc = XDocument.Load(@"C:\Tools\test.xml");
var doc2 = XDocument.Load(@"C:\Tools\test2.xml");
var children = doc2.Root.Element("Details");
var parentNode = doc.Root.Element("Details");
parentNode.ReplaceWith(children);

By the way, your xml are not correct, so you'll get exceptions.

I tried with

<Root>
    <AgencyName name= "Some Agency"/>
    <Originator name= "Some other Agency"/>
    <Type name= "AnonymousType"/>
    <Details/>
</Root>

and

<Root>
    <Details>
        <Detail1>
           asdf
        </Detail1>
        <Detail2>
            asde
        </Detail2>
        <Detail3>
            eere
        </Detail3>
    </Details>
</Root>

and got

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <AgencyName name="Some Agency" />
  <Originator name="Some other Agency" />
  <Type name="AnonymousType" />
  <Details>
    <Detail1>
           asdf
        </Detail1>
    <Detail2>
            asde
        </Detail2>
    <Detail3>
            eere
        </Detail3>
  </Details>
</Root>

Upvotes: 2

Related Questions