1

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.

3
  • 1
    .NET offers many classes for working with XML. There are different ways to do the same job depending on the library you use, whether you have an XSD or not, etc. Did you try anything? Commented Mar 26, 2018 at 12:07
  • @Maxime I tried but i could not achieve it so only posted here . i wanted everyone to completely understand .If you cant help out then its not a problem.Those who have time to read it will post the answer or help me out. Commented Mar 26, 2018 at 12:48
  • 2
    There are multiple root elements in your XmlTemplate. Fix it. Commented Mar 26, 2018 at 13:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You just beat me by a second :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.