How to add an existing Xml string into a XElement

后端 未结 3 1172
醉酒成梦
醉酒成梦 2020-12-11 00:53

How to add an existing Xml string into a XElement?

This code

        var doc = new XDocument(
            new XElement(\"results\", \".         


        
相关标签:
3条回答
  • 2020-12-11 01:12

    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.

    0 讨论(0)
  • 2020-12-11 01:26

    This should work:

    var xmlString = "<result>sometext</result>";
    var xDoc = new XDocument(new XElement("results", XElement.Parse(xmlString)));
    
    0 讨论(0)
  • 2020-12-11 01:26

    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));
    
    0 讨论(0)
提交回复
热议问题