How to insert an XML File into Another XML File at Specific Node C#

I have two XML Files ,the first one is and Named as XMLTemplate

<DataSources>
<DataSource Name="XXXX">
</DataSource>
<DataSource Name="ABC">
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="abc">
<Query> 
</Query>
<ReportSections>
</ReportSections>

and the second xml file is named as XMLGenrated,

<Fields>
<Field >
</Field>
</Fields>

and I need the Output as,

<DataSource Name="XXXX">
    </DataSource>
    <DataSource Name="ABC">
    </DataSource>
    </DataSources>
    <DataSets>
    <DataSet Name="abc">
    <Query> 
    <Fields>
    <Field >
    </Field>
    </Fields>
    </Query>
    <ReportSections>
    </ReportSections> 

Both the Files are in .XML Extension and I dont know how to find the node by its Name Can anyone help me out.

I tried this,

XElement xFileRoot = XElement.Load(XMLTemplate.xml);
XElement xFileChild = XElement.Load(XMLGenerated.xml);
xFileRoot.Add(xFileChild);
xFileRoot.Save(file1.xml);

but the XML adds below the XMLTemplate I dont know how to insert at particular node.

Upvotes: 1

Views: 738

Answers (1)

Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10844

Find the node using Linq to XML and Replace its contents

XElement xFileRoot = XElement.Load(XMLTemplate.xml);
XElement xFileChild = XElement.Load(XMLGenerated.xml);


var queryNode = xFileRoot.Element("Query");

queryNode.ReplaceWith(xFileChild) ;

Based on on this answer - How can I update/replace an element of an XElement from a string?

Be aware that you sample XML files contain multiple root nodes, and that if you need to keep the <Query> node you need to change this.

Upvotes: 1

Related Questions