格式化xml输出

时间:2011-10-16 07:48:56

标签: c# .net xml serialization xml-serialization

我正在使用此方法将对象转换为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"

2 个答案:

答案 0 :(得分:2)

我个人总是发现使用LINQ to XML的手写XML序列化效果很好。它可以根据您的需要灵活调整,您可以以任何方式使其向后和向前兼容,显然您不会得到任何您不想要的额外命名空间或属性。

显然,你的课程越复杂就越复杂,但我发现它对于简单的课程非常有效。这至少是另一种考虑因素。

答案 1 :(得分:2)

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());
        }
    }
}