C# XML CDATA 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/969124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:29:51  来源:igfitidea点击:

XML CDATA Encoding

c#xmlcdata

提问by

I am trying to build an XML document in C# with CDATA to hold the text inside an element. For example..

我正在尝试使用 CDATA 在 C# 中构建一个 XML 文档来保存元素内的文本。例如..

<email>
<![CDATA[[email protected]]]>
</email>

However, when I get the InnerXml property of the document, the CDATA has been reformatted so the InnerXml string looks like the below which fails.

但是,当我获得文档的 InnerXml 属性时,CDATA 已被重新格式化,因此 InnerXml 字符串如下所示,但失败了。

<email>
&lt;![CDATA[[email protected]]]&gt;
</email>

How can I keep the original format when accessing the string of the XML?

访问XML的字符串时如何保持原始格式?

Cheers

干杯

采纳答案by Jon Skeet

Don't use InnerText: use XmlDocument.CreateCDataSection:

不要使用InnerText:使用XmlDocument.CreateCDataSection

using System;
using System.Xml;

public class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("root");
        XmlElement email = doc.CreateElement("email");
        XmlNode cdata = doc.CreateCDataSection("[email protected]");

        doc.AppendChild(root);
        root.AppendChild(email);
        email.AppendChild(cdata);

        Console.WriteLine(doc.InnerXml);
    }
}

回答by elmuerte

See XmlDocument::CreateCDataSection Method for information and examples how to create CDATA nodes in an XML Document

有关如何在 XML 文档中创建 CDATA 节点的信息和示例,请参阅XmlDocument::CreateCDataSection 方法

回答by Marc Gravell

With XmlDocument:

XmlDocument

    XmlDocument doc = new XmlDocument();
    XmlElement email = (XmlElement)doc.AppendChild(doc.CreateElement("email"));
    email.AppendChild(doc.CreateCDataSection("[email protected]"));
    string xml = doc.OuterXml;

or with XElement:

或与XElement

    XElement email = new XElement("email", new XCData("[email protected]"));
    string xml = email.ToString();