1

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 -- Merge XML documents -- but creating an XSLT transform seemed like extra trouble for what seems like a simple operation.)

Community
  • 1
  • 1
Number8
  • 12,322
  • 10
  • 44
  • 69

2 Answers2

4

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
  • 34,223
  • 3
  • 62
  • 80
0

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.
  • 9,280
  • 12
  • 46
  • 50
  • 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 Aug 13 '09 at 21:29