public class Person { public string Name { get; set; } public int Age { get; set; } }
引用内容
<?xml version="1.0"?> <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 class Person { public XmlNode Name { get; set; } //XmlNodeType.CDATA public XmlNode Age { get; set; } //XmlNodeType.Text }
引用内容
<?xml version="1.0"?> <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; 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(); } } }
引用内容
<?xml version="1.0"?> <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 内容: