如何在XmlTextWriter中设置Settings属性,以便我可以在自己的行上编写每个XML属性?

Rob*_*vey 17 c# xml serialization xmlwriter xmltextwriter

我有一些代码,它将一个对象序列化为一个文件.我正在尝试将每个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

如何SettingsXmlTextWriter对象上设置属性,以便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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pol*_*ity 21

使用静态Create()方法XmlWriter.

XmlWriter.Create(filePath, settings);
Run Code Online (Sandbox Code Playgroud)

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


ale*_*a87 5

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

XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
w.Formatting = Formatting.Indented; 
Run Code Online (Sandbox Code Playgroud)

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