添加XML字符串的XElement字符串、XML、XElement

2023-09-07 08:56:53 作者:钩钩手指★卟离卟弃

您好我需要创建从一个字符串,它可以是XML或纯字符串中的XElement。

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

这code

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

生产这种

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

但如果字符串是XML,那么我需要正确的XML

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

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

比XElement.Parse(),因为它会抛出异常,如果是纯文本?

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

推荐答案

请参阅我的Is有一个的XElement相当于XmlWriter.WriteRaw?

从本质上讲,替换的占位符内容的只有当你知道它已经有效的XML 的。

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

这方法也可能会更快。