我有這段代碼,它將一個對象序列化爲一個文件。我試圖讓每個XML屬性在一個單獨的行上輸出。代碼如下所示:如何在XmlTextWriter中設置Settings屬性,以便我可以在自己的行上編寫每個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);
}
}
唯一的問題是,在XmlTextWriter
對象的Settings
屬性爲只讀。
如何在XmlTextWriter
對象上設置Settings
屬性,以便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);
}
}
它沒有實例。它表示它已執行,但創建的對象爲空。注意:我使用XmlTextWriter writer = XmlWriter.Create(filePath,settings)作爲XmlTextWriter;' –
@RobertHarvey - 這意味着'XmlWriter.Create(...)'不會創建'XmlTextWriter'。當你看到輸出時,你會發現它返回一個'XmlWellFormedWriter'。儘管像「XmlWriter」一樣對待它是明智的。 – Polity
那麼我如何獲得它到'XmlTextWriter'? –