0

I'm trying to create a new xml file with parts from other xml files. For example i got these 2 xml files:

file 1:

<root> 
    <persons>
        <person1>
            <name> </name>
            <address> </address>
            <number> </number>
        </person1>
        <person2>
            <name> </name>
            <address> </address>
            <number> </number>
        </person2>
    </persons>
</root>

file 2:

<registration>
    <results>
        <result1>
            <test1> </test1>
            <Test2> </test2>
        </result1>
        <result2>
            <test1> </test1>
            <Test2> </test2>
        </result2>
    </results>
</registration>

The new xml file should look like this:

<combined>
    <persons> 
        <person1>
            <name> </name>
            <address> </address>
            <number> </number>
        </person1>
        <person2>
            <name> </name>
            <address> </address>
            <number> </number>
        </person2>
    </persons>
    <results>
        <result1>
            <test1> </test1>
            <Test2> </test2>
        </result1>
        <result2>
            <test1> </test1>
            <Test2> </test2>
        </result2>
    </results>
</combined>

How can I accomplish this in C# with xmldocument?

EDIT

Some more information, the nodes "persons" and "results" should be put in the new xml document (including "persons" and "results").

Yustme
  • 6,125
  • 22
  • 75
  • 104

2 Answers2

2

Basically:

var doc1 = XElement.Load(file1);
var doc2 = XElement.Load(file2);

var combined = new XElement("combined", doc1.Descendants("person"), doc2);

combined.Save(file3);
H H
  • 263,252
  • 30
  • 330
  • 514
  • Hi, I updated my question. Also, the document should be saved to disk. Should the var 'combined' be converted to something XDocument() understands? – Yustme May 14 '12 at 17:46
  • Your sample data is not entirely consistent but it should be easy to work out the exact selection from doc1 and doc2. – H H May 14 '12 at 17:48
  • It should now be consistent. I was making a quick example on this site. I just edit everything in notepad++. – Yustme May 14 '12 at 17:51
1
XElement root1 = XElement.Load(file1);
XElement root2 = XElement.Load(file2);
XElement combined = new XElement("combined");

foreach(XElement node1 in root1.Elements())
    combined.Add(node1);

foreach(XElement node2 in root2.Elements())
    combined.Add(node2);

combined.Save(file3);
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69