前段时间写了一个关于XML序列化和反序列化的(),最近突然发现一个问题,就是当XML节点值为空时,序列化后的XML节点会是这种形式的<node />。但是我们如果需要<node></node>这种形式的该如何写呢。先看看代码吧
工具类和测试对象
public class XmlTextWriterTest : XmlTextWriter { public XmlTextWriterTest(Stream w, Encoding encoding) : base(w, encoding) { } public XmlTextWriterTest(TextWriter w) : base(w) { } public XmlTextWriterTest(string filename, Encoding encoding) : base(filename, encoding) { } public override void WriteEndElement() { base.WriteFullEndElement(); } } public static class Utility { public static string XMLSerialization(object obj) { string result = string.Empty; if (obj != null) { try { XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); xmlns.Add(string.Empty, string.Empty); XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType()); using (MemoryStream memoryStream = new MemoryStream()) { XmlTextWriterTest writer = new XmlTextWriterTest(memoryStream, Encoding.Default); writer.Formatting = Formatting.Indented; xmlSerializer.Serialize(writer, obj, xmlns); writer.Flush(); writer.Close(); result = Encoding.Default.GetString(memoryStream.ToArray()); } } catch (Exception ex) { throw ex; } } return result; } public static T XMLDeSerialization(string xml) { T result = default(T); XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); try { using (StringReader stringReader = new StringReader(xml)) { result = (T)xmlSerializer.Deserialize(stringReader); } } catch (Exception ex) { throw ex; } return result; } } [Serializable] [XmlRoot("school")] public class TestObject { [XmlAttribute("descri")] public string descri = "Eddy's xml serializaion demo"; [XmlElement("English")] public English english; [XmlElement("Chinese")] public Chinese chinese; } public class English { [XmlElement("Teacher")] public string Teacher = string.Empty; [XmlElement("Room")] public string Room = "202"; } public class Chinese { [XmlElement("Teacher")] public string Teacher = "Eddy"; [XmlElement("Room")] public string Room = "203"; [XmlElement("Students")] public Students students; } public class Students { [XmlElement("Student")] public List student; } public class Student { [XmlAttribute("Name")] public string Name = string.Empty; [XmlAttribute("No")] public string No = string.Empty; [XmlAttribute("Age")] public string Age = "19"; }
调用示例
TestObject obj = new TestObject() { chinese = new Chinese() { students = new Students() { student = new List(){ new Student(), new Student() } } }, english = new English() }; string xml = Utility.XMLSerialization(obj); TestObject obj1 = Utility.XMLDeSerialization (xml);
达到目的的关键就是下面这一部分代码,没错,重写了WriteEndElement方法。从字面意思可以看出,它就是用来写完整的结束标志,如:<node></node>的。
public override void WriteEndElement() { base.WriteFullEndElement(); }
好了,去看电影了,雨果看了半集,继续。