序列化成一个XML片段 - 不是XML文档 [英] Serialize into an XML Fragment - not XML Document

查看:168
本文介绍了序列化成一个XML片段 - 不是XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何序列化XML序列化对象到XML片段(没有XML声明,也没有命名空间引用的根元素)?

How do I serialize an XML-serializable object to an XML fragment (no XML declaration nor namespace references in the root element)?

推荐答案

下面是一个黑客十岁上下的方式做到这一点,而无需将整个输出字符串到如下:

Here is a hack-ish way to do it without having to load the entire output string into an XmlDocument:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public class Example
{
    public String Name { get; set; }

    static void Main()
    {
        Example example = new Example { Name = "Foo" };

        XmlSerializer serializer = new XmlSerializer(typeof(Example));

        XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
        emptyNamespace.Add(String.Empty, String.Empty);

        StringBuilder output = new StringBuilder();

        XmlWriter writer = XmlWriter.Create(output,
            new XmlWriterSettings { OmitXmlDeclaration = true });
        serializer.Serialize(writer, example, emptyNamespace);

        Console.WriteLine(output.ToString());
    }
}

这篇关于序列化成一个XML片段 - 不是XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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