在序列化对象时,在.Net中设置StandAlone = Yes

时间:2011-08-09 13:40:58

标签: .net serialization xml-serialization

在下面的代码中我想为xml设置“standalone = yes”,我该怎么做?

Dim settings As New Xml.XmlWriterSettings
settings.Encoding = encoding

Using stream As New IO.MemoryStream, xtWriter As Xml.XmlWriter = _
    Xml.XmlWriter.Create(stream, settings)
    serializer.Serialize(xtWriter, obj)
    Return encoding.GetString(stream.ToArray())
End Using

例如,我有这个:

<?xml version="1.0" encoding="utf-8"?>

但我想要这个:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

2 个答案:

答案 0 :(得分:15)

我找到了一种更优雅的方法:只需在setTabWidget实例上调用WriteStartDocument(true) - 此代码序列化XmlWriter并将生成的XML输出到控制台。

首先,如果您使用data,则需要稍微调整一下以强制使用UTF-8,但keep this in mind

  

将XML文档序列化为.NET字符串时,编码必须设置为UTF-16。字符串在内部存储为UTF-16,因此这是唯一有意义的编码。如果要以不同的编码存储数据,则使用字节数组。

StringWriter
public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }
}

using (var sw = new Utf8StringWriter()) using (var xw= XmlWriter.Create(sw, new XmlWriterSettings{Indent = true})) { xw.WriteStartDocument(true); // that bool parameter is called "standalone" var namespaces = new XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); var xmlSerializer = new XmlSerializer(typeof(data)); xmlSerializer.Serialize(xw, data); Console.WriteLine(sw.ToString()); } 真的感觉像指定WriteStartDocument(true)的惯用方式。输出标题如下所示:

standalone=true

答案 1 :(得分:7)

如果你想这样做,那么你需要使用WriteProcessingInstruction方法并手动写出来。

    Using stream As New IO.MemoryStream, xtWriter As Xml.XmlWriter = Xml.XmlWriter.Create(stream, settings)
        xtWriter.WriteProcessingInstruction("xml", "version=""1.0"" encoding=""UTF-8"" standalone=""yes""")
        serializer.Serialize(xtWriter, obj)
        Return encoding.GetString(stream.ToArray())
    End Using