0

I have an xml document that follows:

-<Machines>


-<Machine>


-<InstallPath >

<Component "/>

<Component "/>

<Component "/>

<Component "/>

<Component "/>


</InstallPath>

</Machine>
</Machines>

I need to add a root Manifest element before Machines pragmatically using C#.

I tried the following code and I get an error saying that the document is not properly constructed.

Here is the code I am trying:

using (XmlReader reader = cmd.ExecuteXmlReader())
                    {
                        XDocument doc = XDocument.Load(reader);
                        doc.Root.AddBeforeSelf(new XElement("Manifest"));
                        string path = outputPath + "\\" + xmlFileName;

                        doc.Save(path);    
                    }
Mattaceten
  • 129
  • 2
  • 5
  • 14

2 Answers2

1

XML can only have one "root" element. So the structure you're wanting is not valid:

<Manifest>
    ...
</Manifest>
<Machines>
    ...
</Machines>

If you want two sibling elements, they would need to be contained in another parent element.

I want the Manifest element to surround the Machines element and the Machines element to contain the rest of the xml

Then you need to create a new document:

XDocument newDoc = new XDocument(new XElement("Manifest", doc.Root));

This creates a new XDocument with a Manifest root tag, whose content is the root (and contents) of the original document.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Sorry Im complete new to xml, I dont want two "root elements" I want the Manifest element to surround the Machines element and the Machines element to contain the rest of the xml if that makes sense – Mattaceten Mar 23 '17 at 16:15
  • So if it is possible to insert the Manifest element around the Machines element and have the Manifest element as the root instead of the Machines that would be Ideal. – Mattaceten Mar 23 '17 at 16:16
1

Create a new element with the current Root and put it in a new XDocument:

XDocument newDoc = new XDocument(new XElement("Manifest", doc.Root));
Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27