2011-11-23 19 views
14

Ho questo bit di codice, che serializza un oggetto in un file. Sto cercando di ottenere ogni attributo XML per l'output su una riga separata. Il codice è simile al seguente:Come si imposta la proprietà Settings in XmlTextWriter, in modo che sia possibile scrivere ogni attributo XML sulla propria riga?

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

L'unico problema è, la proprietà dell'oggetto XmlTextWriterSettings è di sola lettura.

Come impostare la proprietà sull'oggetto XmlTextWriter, in modo che l'impostazione NewLineOnAttributes funzioni?


Beh, ho pensato che avevo bisogno di un XmlTextWriter, dal momento che è una classe XmlWriterabstract. Un po 'di confusione se me lo chiedi. codice di lavoro finale è qui:

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

risposta

18

Utilizzare il Create() metodo statico di XmlWriter.

XmlWriter.Create(filePath, settings); 

Si noti che è possibile impostare la proprietà NewLineOnAttributes nelle impostazioni.

+0

Non ha istanziare. Dice che è stato eseguito, ma l'oggetto creato è nullo. Nota: ho usato 'XmlTextWriter writer = XmlWriter.Create (filePath, settings) come XmlTextWriter;' –

+0

@RobertHarvey - Ciò significa che 'XmlWriter.Create (...)' non crea un 'XmlTextWriter'. Quando guardi l'output, troverai che restituisce un 'XmlWellFormedWriter'. Sarebbe saggio però trattarlo come un 'XmlWriter'. – Polity

+0

Quindi, come ottengo un 'XmlTextWriter'? –

Problemi correlati