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);
}
XML can only have one "root" element. So the structure you're wanting is not valid:
If you want two sibling elements, they would need to be contained in another parent element.
Then you need to create a new document:
This creates a new
XDocumentwith aManifestroot tag, whose content is the root (and contents) of the original document.