How do I set the Settings property in XmlTextWriter, so that I can write each XML attribute on its own line?

自闭症网瘾萝莉.ら 提交于 2019-12-19 05:07:45

问题


I have this bit of code, which serializes an object to a file. I'm trying to get each XML attribute to output on a separate line. The code looks like this:

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);
    }
}

The only problem is, the Settings property of the XmlTextWriter object is read-only.

How do I set the Settings property on the XmlTextWriter object, so that the NewLineOnAttributes setting will work?


Well, I thought I needed an XmlTextWriter, since XmlWriter is an abstract class. Kinda confusing if you ask me. Final working code is here:

/// <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);
    }
}

回答1:


Use the static Create() method of XmlWriter.

XmlWriter.Create(filePath, settings);

Note that you can set the NewLineOnAttributes property in the settings.




回答2:


I know the question is old, anyway it's actually possible to set indentation for the XMLTextWriter. Unlike with the XMLwriter, you don't have to pass through the settings; you should use the Formatting property:

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

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



来源:https://stackoverflow.com/questions/8237165/how-do-i-set-the-settings-property-in-xmltextwriter-so-that-i-can-write-each-xm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!