[英]XML CDATA Encoding
I am trying to build an XML document in C# with CDATA to hold the text inside an element. 我正在尝试使用CDATA在C#中构建XML文档,以将文本保存在元素中。 For example..
例如..
<email>
<![CDATA[test@test.com]]>
</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>
<![CDATA[test@test.com]]>
</email>
How can I keep the original format when accessing the string of the XML? 访问XML字符串时如何保持原始格式?
Cheers 干杯
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("test@test.com");
doc.AppendChild(root);
root.AppendChild(email);
email.AppendChild(cdata);
Console.WriteLine(doc.InnerXml);
}
}
With XmlDocument
: 使用
XmlDocument
:
XmlDocument doc = new XmlDocument();
XmlElement email = (XmlElement)doc.AppendChild(doc.CreateElement("email"));
email.AppendChild(doc.CreateCDataSection("test@test.com"));
string xml = doc.OuterXml;
or with XElement
: 或使用
XElement
:
XElement email = new XElement("email", new XCData("test@test.com"));
string xml = email.ToString();
有关如何在XML文档中创建CDATA节点的信息和示例,请参见XmlDocument :: CreateCDataSection方法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.