Dot-Net
序列化對象時在 .Net 中設置 StandAlone = Yes
在下面的程式碼中,我想將“standalone = yes”設置為 xml,我該怎麼做?
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"?>
如果你想這樣做,那麼你需要使用
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
我找到了一種更優雅的方法:只需呼叫
WriteStartDocument(true)您的XmlWriter實例 - 此程式碼序列化data並將生成的 XML 輸出到控制台。首先,如果您使用的是 a ,則
StringWriter需要對其進行一些調整以強制使用 UTF-8,但請記住這一點:將 XML 文件序列化為 .NET 字元串時,編碼必須設置為 UTF-16。字元串在內部儲存為 UTF-16,因此這是唯一有意義的編碼。如果您想以不同的編碼儲存數據,請改用字節數組。
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。輸出標題如下所示:<?xml version="1.0" encoding="utf-8" standalone="yes"?>