[英]How to use .NET XmlSerializer to serialzie null and empty value with special format
I want to use the .NET XmlSerializer class to serialize a class object to an XML string. 我想使用.NET XmlSerializer类将类对象序列化为XML字符串。 both null string and empty string should be serialized. 应该序列化空字符串和空字符串。
if a property value is null then XML format like 如果属性值为null,那么XML格式就像
<property />
if a property value is an empty string, then the serialized XML format is 如果属性值是空字符串,则序列化XML格式为
<property></property>
When you need custom serialization, you'll need to implement your own implementation of the IXmlSerialization
interface. 当您需要自定义序列化时,您需要实现自己的IXmlSerialization
接口实现。 This provides custom formatting for XML serialization and deserialization. 这为XML序列化和反序列化提供了自定义格式。 For example : 例如 :
public class Person : IXmlSerializable
{
// Private state
private string personName;
// Constructors
public Person (string name)
{
personName = name;
}
public Person ()
{
personName = null;
}
// Xml Serialization Infrastructure
public void WriteXml (XmlWriter writer)
{
writer.WriteString(personName);
}
public void ReadXml (XmlReader reader)
{
personName = reader.ReadString();
}
public XmlSchema GetSchema()
{
return(null);
}
// Print
public override string ToString()
{
return(personName);
}
}
You can use properties of class without initialize. 您可以在不初始化的情况下使用类的属性。 It will like: 它会像:
class XmlData{
public string Person;
public XmlData(){
Person=null;
}
}
class Program{
static void Main(){
var xmlTaplate=new XmlData();//in this step property Person is null
var serializer = new XmlSerializer(typeof(xmlTemplate));
using (TextWriter writer = new StreamWriter(@"person.xml"))
{
serializer.Serialize(writer, details);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.