I am trying to build an XML document in C# with CDATA to hold the text inside an element. 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.
<email>
<![CDATA[test@test.com]]>
</email>
How can I keep the original format when accessing the string of the XML?
Cheers
Don't use InnerText
: use 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 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 email = new XElement("email", new XCData("test@test.com"));
string xml = email.ToString();
有关如何在XML文档中创建CDATA节点的信息和示例,请参见XmlDocument :: CreateCDataSection方法 。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.