序列化.NET对象并省略DOCTYPE? [英] Serialize a .net object and omit the doctype?

查看:166
本文介绍了序列化.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)
    {
            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.

推荐答案

<一个href="http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx"><$c$c>XmlWriterSettings有一个属性省略XML声明(<一href="http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.omitxmldeclaration.aspx"><$c$c>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();
}

这篇关于序列化.NET对象并省略DOCTYPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆