tags:

views:

231

answers:

2

I have several XDocuments that look like:

<Test>
  <element
      location=".\jnk.txt"
      status="(modified)"/>
 <element
     location=".\jnk.xml"
     status="(overload)"/>
</Test>

In C#, I create a new XDocument:

XDocument mergedXmlDocs = new XDocument(new XElement("ACResponse"));

And try to add the nodes from the other XDocuments:

for (ti = 0; (ti < 3); ++ti)
{
    var query = from xElem in xDocs[(int)ti].Descendants("element")
        select new XElement(xElem);

    foreach (XElement xElem in query)
    { 
        mergedXmlDocs.Add(xElem);
    }
}

At runtime I get an error about how the Add would create a badly-formed document.
What am I doing wrong?
Thanks...

(I saw this question -- http://stackoverflow.com/questions/80609/merge-xml-documents -- but creating an XSLT transform seemed like extra trouble for what seems like a simple operation.)

A: 

I am not sure what programming language you are using, but for most programming languages there is extensive XML support classes. Most of them allow parsing and even adding of element. I would have 1 main file that I would keep around and then parse each new one adding the elements from the new one into the master.

EDIT: Sorry it looks like you are already doing exactly this.

jW
That's what I am trying to do... Add all the 'element' elements from several XDocuments to the mergedXmlDocs XDocument.The runtime error is: "This operation would create an incorrectly structured document."
Number8
+2  A: 

You are very close. Trying changing the line

mergedXmlDocs.Add(xElem);

to

mergedXmlDocs.Root.Add(xElem);

The problem is that each XML document can only contain 1 root node. Your existing code is trying to add all of the nodes at the root level. You need to add them to the existing top level node instead.

David
Thanks, I didn't look deeply enough in to XDocument's properties...
Number8