Adding XML string to XElement

我的未来我决定 提交于 2019-12-24 02:55:51

问题


Hi I need to create an XElement from a string, which can be xml or plain string.

This code

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

produces this

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

But if the string is XML, then I need proper XMl

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

Any ideas other than XElement.Parse() because it will throw exception if it is plain text?


回答1:


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.




回答2:


I don't know if there is other way around and it also doesn't look as a best way but you can achieve it like this:

object resultContent;

if (condition)
{
    //if content is XmlElement
    resultContent = new XElement("result", "....");
}
else
{
    resultContent = "Text";
}

XDocument xDoc = new XDocument(new XElement("results", resultContent));



回答3:


How about doing this:

XElement.Parse(String.Format("<Results>{0}</Results>",possibleXMLString));

... and before someone objects to this employing .Parse() method, which is mentioned by OP, please note that this is not the usage that was mentioned.



来源:https://stackoverflow.com/questions/16586443/adding-xml-string-to-xelement

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