C#调用XmlSerializer序列化时生成CDATA节点解决方法
{
public string Name { get; set; }
public int Age { get; set; }
}
<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>dnawo</Name>
<Age>100</Age>
</Person>
例2
{
public XmlNode Name { get; set; } //XmlNodeType.CDATA
public XmlNode Age { get; set; } //XmlNodeType.Text
}
<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name><![CDATA[dnawo]]></Name>
<Age>100</Age>
</Person>
例1的实体类我们比较常用,赋值取值方便,但序列化时不能生成CDATA节点,例2的实体类序列化时可以生成CDATA节点,但使用不方便,于是将两个例子优点做了下结合:
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
public partial class Person
{
[XmlIgnore]
public string Name { get; set; }
[XmlIgnore]
public int Age { get; set; }
}
public partial class Person
{
[XmlElement("Name")]
public XmlNode aaa
{
get
{
XmlNode node = new XmlDocument().CreateNode(XmlNodeType.CDATA, "", "");
node.InnerText = Name;
return node;
}
set { } //省略则aaa不会被序列化
}
[XmlElement("Age")]
public XmlNode bbb
{
get
{
XmlNode node = new XmlDocument().CreateNode(XmlNodeType.Text, "", "");
node.InnerText = Age.ToString();
return node;
}
set { } //省略则bbb不会被序列化
}
}
class Program
{
static void Main(string[] args)
{
string result = string.Empty;
Person person = new Person() { Name = "dnawo", Age = 100 };
using (MemoryStream output = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(person.GetType());
serializer.Serialize(output, person);
result = Encoding.UTF8.GetString(output.ToArray());
}
Console.WriteLine(result);
Console.ReadKey();
}
}
}
<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name><![CDATA[dnawo]]></Name>
<Age>100</Age>
</Person>
常见问题
问:为什么例2实体类属性类型不直接用XmlCDataSection、XmlText?
答:用XmlCDataSection没问题,而XmlText序列化时会失败,提示反射类型“System.Xml.XmlText”出错。
参考资料
[1].使用 XmlSerializer 控制序列化生成 CDATA 内容:http://blog.csdn.net/hwj383/article/details/5780962
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2017-06-07 c# 网站生成静态页面
2016-06-07 基于Metronic的Bootstrap开发框架经验总结(9)--实现Web页面内容的打印预览和保存操作
2016-06-07 jQuery插件之ajaxFileUpload
2016-06-07 使用Entity Framework时要注意的一些性能问题
2016-06-07 jquery 图片上传本地预览V1.2
2015-06-07 JS正则表达式验证数字非常全