標籤:tle tostring 1.0 gets .text code version org ref
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 內容:http://blog.csdn.net/hwj383/article/details/5780962
C#調用XmlSerializer序列化時產生CDATA節點解決方案