gpt4 book ai didi

c# - 如何使用 XmlSerializer 将字符串序列化为 CDATA?

转载 作者:IT王子 更新时间:2023-10-29 03:38:40 24 4
gpt4 key购买 nike

是否可以通过某种属性使用 .Net XmlSerializer 将字符串序列化为 CDATA?

最佳答案

[Serializable]
public class MyClass
{
public MyClass() { }

[XmlIgnore]
public string MyString { get; set; }
[XmlElement("MyString")]
public System.Xml.XmlCDataSection MyStringCDATA
{
get
{
return new System.Xml.XmlDocument().CreateCDataSection(MyString);
}
set
{
MyString = value.Value;
}
}
}

用法:

MyClass mc = new MyClass();
mc.MyString = "<test>Hello World</test>";
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, mc);
Console.WriteLine(writer.ToString());

输出:

<?xml version="1.0" encoding="utf-16"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyString><![CDATA[<test>Hello World</test>]]></MyString>
</MyClass>

关于c# - 如何使用 XmlSerializer 将字符串序列化为 CDATA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1379888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com