Question

How to add an existing Xml string into a XElement?

This code

        var doc = new XDocument(
            new XElement("results", "<result>...</result>")
        );

of course produces this

  <results>&lt;result&gt;&lt;/result&gt;</results>

but I need this

  <results><result>...</result></results>

Any ideas?

Was it helpful?

Solution

This should work:

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top