简体   繁体   English

将XML字符串添加到XElement

[英]Adding XML string to XElement

Hi I need to create an XElement from a string, which can be xml or plain string. 嗨,我需要从字符串创建XElement,它可以是xml或纯字符串。

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 但是,如果字符串是XML,那么我需要正确的XMl

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

Any ideas other than XElement.Parse() because it will throw exception if it is plain text? XElement.Parse()之外的任何其他想法,因为如果它是纯文本,它将抛出异常?

See my answer on Is there an XElement equivalent to XmlWriter.WriteRaw? 请参阅我的答案, 是否存在与XmlWriter.WriteRaw等效的XElement?

Essentially, replace a placeholder for the content only if you know it's already valid XML . 本质上, 只有在您知道内容已经是有效XML的情况下 ,才替换占位符。

var d = new XElement(root, XML_PLACEHOLDER);
var s = d.ToString().Replace(XML_PLACEHOLDER, child);

This method may also be faster. 此方法也可能更快。

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

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. ...并且在有人反对使用.Parse()方法(OP提到过)之前,请注意,这不是所提到的用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM