How to add an existing Xml string into a XElement How to add an existing Xml string into a XElement xml xml

How to add an existing Xml string into a XElement


This should work:

var xmlString = "<result>sometext</result>";var xDoc = new XDocument(new XElement("results", XElement.Parse(xmlString)));


The answer by Sani Singh Huttunen put me on the right track, but it only allows one result element in the results element.

var xmlString = "<result>sometext</result><result>alsotext</result>";

fails with the System.Xml.XmlException

There are multiple root elements.

I solved this by moving the results element to the string literal

var xmlString = "<results><result>sometext</result><result>alsotext</result></results>";

so that it had only one root element and then added the parsed string directly to the parent element, like this:

parent.Add(XElement.Parse(xmlString));


See my answer on Is there an XElement equivalent to XmlWriter.WriteRaw?

Essentially, replace a placeholder for the content only if you know it's already valid XML.

var d = new XElement(root, XML_PLACEHOLDER);var s = d.ToString().Replace(XML_PLACEHOLDER, child);

This method may also be faster than parsing it with XElement.Parse.