0

I am not experienced with LinQ and Xml. I need to join two xml files as follows

file1.xml

<?xml version="1.0" encoding="utf-8"?>
<RootNode>
<SubNode>

<NodeA id="1" />
<NodeB id="2" />
<NodeC id="3" />

</SubNode>
<LonelyNode/>
</RootNode>

file2.xml

<?xml version="1.0" encoding="utf-8"?>
<RootNode>
<SubNode>

<NodeD id="1" />
<NodeE id="2" />
<NodeF id="3" />

</SubNode>
<LonelyNode/>
</RootNode>

actual code

string fileName1 = "file1.xml";
string fileName2 = "file2.xml";

string filePath_file1 = String.Format("{0}{1}", rootDirectory, fileName1);
string filePath_file2 = String.Format("{0}{1}", rootDirectory, fileName2);

// create xml document from file1.xml
var document = XDocument.Load(filePath_file1.xml);

// add file2.xml
document.Root.Add(XDocument.Load(filePath_file2).Root.Elements());
Console.WriteLine(document);
Console.ReadLine();

actual output

<?xml version="1.0" encoding="utf-8"?>
<RootNode>

<SubNode>
  <NodeA id="1" />
  <NodeB id="2" />
  <NodeC id="3" />
</SubNode>
<LonelyNode/>

<SubNode>
  <NodeD id="1" />
  <NodeE id="2" />
  <NodeF id="3" />
</SubNode>
<LonelyNode/>

</RootNode>

wanted output

<?xml version="1.0" encoding="utf-8"?>
<RootNode>
<SubNode>

<NodeA id="1" />
<NodeB id="2" />
<NodeC id="3" />
<NodeD id="1" />
<NodeE id="2" />
<NodeF id="3" />

</SubNode>
<LonelyNode/>
</RootNode>

How can I be specific of node to copy to first file ? I want to copy <SubNode> content only from file2.

Muflix
  • 6,192
  • 17
  • 77
  • 153

1 Answers1

0

You are almost there, instead of adding to Root find SubNode element using Element method and then add elements from other document.

document.Root
        .Element("SubNode")
        .Add(XDocument.Load(filePath_file2).Root.Element("SubNode").Elements());

Check this Demo

Output:

 <RootNode>
  <SubNode>
    <NodeA id="1" />
    <NodeB id="2" />
    <NodeC id="3" />
    <NodeD id="1" />
    <NodeE id="2" />
    <NodeF id="3" />
  </SubNode>
  <LonelyNode />
</RootNode>
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
  • It works, thank you! it is also possible to sort the SubNode content by node name (NodeA, NodeB, ... ) ? – Muflix Jun 22 '16 at 09:35
  • I found solution for sorting here http://stackoverflow.com/questions/3469801/sorting-all-the-elements-in-a-xdocument thank you – Muflix Jun 22 '16 at 10:31