public class Person
{
public string Name {get; set;}
public int Age {get; set;}
}
Reference content <?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>
Example 2
Copy content to Clipboard program code public class person
{
Public XmlNode Name {get; set;}//xmlnodetype.cdata
Public XmlNode age {get; set;}//xmlnodetype.text
}
Reference content <?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>
Example 1 of the entity class we are more commonly used, the value of the assignment is convenient, but the serialization can not generate CDATA nodes, example 2 of the entity class to generate CDATA nodes, but the use of inconvenient, so the two examples of the advantages of a combination:
Copy content to Clipboard program code 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 {}//Omit AAA will not be serialized
}
[XmlElement ("Age")]
Public XmlNode BBB
{
Get
{
XmlNode node = new XmlDocument (). CreateNode (XmlNodeType.Text, "", "");
Node. InnerText = Age.tostring ();
return node;
}
set {}//omit the BBB will not be serialized
}
}
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 ();
}
}
}
Reference content <?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>
Problems
Q: Why does the example 2 entity class attribute type not be used directly with Xmlcdatasection, XmlText?
A: With Xmlcdatasection no problem, and XmlText serialization will fail, prompting the reflection type "System.Xml.XmlText" error.
Resources
[1]. Use XmlSerializer to control serialization to generate CDATA content: http://blog.csdn.net/hwj383/article/details/5780962
C # calls XmlSerializer serialization when generating CDATA node resolution