使用XmlSerializer序列化一个对象,要求把空节点表示成开始和结束标记对:
当前格式:<Wards />
期望格式:<Wards></Wards>
网上搜了一下, C# - XmlSerializer Serialize empty variable to use both tags?的解决方法是:
public class XmlTextWriterFull : XmlTextWriter {
public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }
public XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }
public XmlTextWriterFull(TextWriter sink) : base(sink) { }
public override void WriteEndElement() {
base.WriteFullEndElement();
}
}
public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }
public XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }
public XmlTextWriterFull(TextWriter sink) : base(sink) { }
public override void WriteEndElement() {
base.WriteFullEndElement();
}
}
然后我这么调用:
MemoryStream stream = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(message.GetType());
XmlTextWriter writer = new XmlTextWriterFull(stream, Encoding.Unicode);
serializer.Serialize(writer, message);
StreamReader reader = new StreamReader(stream, Encoding.Unicode);
stream.Position = 0;
string xml = reader.ReadToEnd();
stream.Close();
writer.Close();
reader.Close();
XmlSerializer serializer = new XmlSerializer(message.GetType());
XmlTextWriter writer = new XmlTextWriterFull(stream, Encoding.Unicode);
serializer.Serialize(writer, message);
StreamReader reader = new StreamReader(stream, Encoding.Unicode);
stream.Position = 0;
string xml = reader.ReadToEnd();
stream.Close();
writer.Close();
reader.Close();
可惜始终不成功。