序列化.net对象并省略doctype?

时间:2012-10-04 14:21:20

标签: c# .net xml xml-serialization

我已经编写了一些.net代码来使用XMLSerializer类序列化对象。

    public static string serialize(object o)
    {
            Type type = o.GetType();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);                
            System.IO.StringWriter writer = new System.IO.StringWriter();
            serializer.Serialize(writer, o);                
            return writer.ToString();         
    }

输出如下:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <string>a</string>
  <string>b</string>
  <string>c</string>
</ArrayOfString>

这很好,但我真正想要的是在开头没有XML doctype声明的情况下只获取根节点。

我想这样做的原因是因为我想将XML序列化对象的根元素用作另一个XML文档的一部分。

1 个答案:

答案 0 :(得分:10)

XmlWriterSettings有一个省略XML声明(OmitXmlDeclaration)的属性:

public static string Serialize(object obj)
{
    var builder = new StringBuilder();
    var xmlSerializer = new XmlSerializer(obj.GetType());
    using (XmlWriter writer = XmlWriter.Create(builder,
        new XmlWriterSettings() { OmitXmlDeclaration = true }))
    {
        xmlSerializer.Serialize(writer, obj);
    }
    return builder.ToString();
}