格式化XML输出
本文关键字:输出 XML 格式化 | 更新日期: 2023-09-27 18:11:36
我使用这个方法将对象转换为XML:
protected XmlDocument SerializeAnObject(object obj)
{
XmlDocument doc = new XmlDocument();
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
try
{
serializer.WriteObject(stream, obj);
stream.Position = 0;
doc.Load(stream);
return doc;
}
finally
{
stream.Close();
stream.Dispose();
}
}
最后我得到这样的东西:
<CaCT>
<CTC i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/a.b.BusinessEntities.InnerEntities" />
<CTDescr xmlns="http://schemas.datacontract.org/2004/07/a.b.BusinessEntities.InnerEntities">blabla</CTDescr>
<CaId>464</CaId>
</CaCT>
如何去掉i:nil="true"
和xmlns="http://schemas.datacontract.org/2004/07/a.b.BusinessEntities.InnerEntities"
我个人总是发现用LINQ to XML进行手写的XML序列化效果很好。它很灵活,你可以用任何你想要的方式使它向后和向前兼容,显然你不会有任何你不想要的额外的名称空间或属性。
显然,你的类越复杂,它就越复杂,但我发现它对简单的类工作得很好。
protected string SerializeAnObject(object obj)
{
XmlSerializerNamespaces xmlNamespaces = new XmlSerializerNamespaces();
xmlNamespaces.Add("", "");
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter stream = XmlWriter.Create(ms, writerSettings))
{
serializer.Serialize(stream, obj, xmlNamespaces);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}