2011-11-23 71 views
14

我有這段代碼,它將一個對象序列化爲一個文件。我試圖讓每個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,因爲XmlWriterabstract類。如果你問我,有點令人困惑。 最後的工作代碼是在這裏:

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

回答

18

使用的XmlWriter靜態Create()方法。

XmlWriter.Create(filePath, settings); 

請注意,您可以在設置中設置NewLineOnAttributes屬性。

+0

它沒有實例。它表示它已執行,但創建的對象爲空。注意:我使用XmlTextWriter writer = XmlWriter.Create(filePath,settings)作爲XmlTextWriter;' –

+0

@RobertHarvey - 這意味着'XmlWriter.Create(...)'不會創建'XmlTextWriter'。當你看到輸出時,你會發現它返回一個'XmlWellFormedWriter'。儘管像「XmlWriter」一樣對待它是明智的。 – Polity

+0

那麼我如何獲得它到'XmlTextWriter'? –

相關問題