How to add an existing Xml string into a XElement

巧了我就是萌 提交于 2019-12-17 20:34:34

问题


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?


回答1:


This should work:

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



回答2:


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));



回答3:


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.



来源:https://stackoverflow.com/questions/1414561/how-to-add-an-existing-xml-string-into-a-xelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!