序列化.NET对象并省略DOCTYPE?对象、序列化、NET、DOCTYPE

由网友(夨忆。)分享简介:我已经写了一些.NET code。使用XMLSerializer类序列化对象。I've written some .net code to serialize an object using the XMLSerializer class.public static string serialize(object o...

我已经写了一些.NET code。使用XMLSerializer类序列化对象。

I've written some .net code to serialize an object using the XMLSerializer class.

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

输出看起来是这样的:

The output looks like this:

<?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声明开头。

That's great, but what I would really like is to get just the root node without the XML doctype declaration at the beginning.

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

The reason I want to do this is because I would like to use the root element of the XML serialized object as part of another XML document.

推荐答案

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();
}
阅读全文

相关推荐

最新文章