19

我有这段代码,它将一个对象序列化为一个文件。我试图让每个 XML 属性在单独的行上输出。代码如下所示:

public static void ToXMLFile(Object obj, string filePath)
{
    XmlSerializer serializer = new XmlSerializer(obj.GetType());

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.NewLineOnAttributes = true;

    XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
    writer.Settings = settings; // Fails here.  Property is read only.

    using (Stream baseStream = writer.BaseStream)
    {
        serializer.Serialize(writer, obj);
    }
}

唯一的问题是,对象的Settings属性XmlTextWriter是只读的。

如何Settings在对象上设置属性XmlTextWriter,以便NewLineOnAttributes设置生效?


好吧,我想我需要一个XmlTextWriter, 因为XmlWriter是一个abstract类。如果你问我,有点令人困惑。 最终工作代码在这里:

/// <summary>
/// Serializes an object to an XML file; writes each XML attribute to a new line.
/// </summary>
public static void ToXMLFile(Object obj, string filePath)
{
    XmlSerializer serializer = new XmlSerializer(obj.GetType());

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.NewLineOnAttributes = true;

    using (XmlWriter writer = XmlWriter.Create(filePath, settings))
    {
        serializer.Serialize(writer, obj);
    }
}
4

2 回答 2

23

使用 的静态Create()方法XmlWriter

XmlWriter.Create(filePath, settings);

请注意,您可以NewLineOnAttributes在设置中设置属性。

于 2011-11-23T04:09:05.187 回答
5

我知道这个问题很老了,无论如何实际上可以为XMLTextWriter. 与 不同XMLwriter,您不必通过设置;您应该使用该Formatting属性:

XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
w.Formatting = Formatting.Indented; 

请参阅 https://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.formatting(v=vs.110).aspx

于 2017-01-13T12:13:44.520 回答