Domanda

Le scrivo alcuni dati in un file XML ... ma quando l'ho aperto tutti i valori sono in una sola riga ... come si può scrivere in un formato leggibile? Cioè ogni nodo nuova linea e il rientro?

FileStream fs = new FileStream("myfile.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement("myfile");                 

w.WriteElementString("id", id.Text);
w.WriteElementString("date", dateTimePicker1.Text);
w.WriteElementString("version", ver.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();
È stato utile?

Soluzione

Usa un XmlTextWriter invece di XmlWriter e quindi impostare le proprietà Indentation.

Esempio

string filename = "MyFile.xml";

using (FileStream fileStream = new FileStream(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fileStream))
using (XmlTextWriter xmlWriter = new XmlTextWriter(sw))
{
  xmlWriter.Formatting = Formatting.Indented;
  xmlWriter.Indentation = 4;

  // ... Write elements
}

A seguito di un commento @jumbo, questo potrebbe essere realizzata anche come in .NET 2.

var filename = "MyFile.xml";
var settings = new XmlWriterSettings() 
{
    Indent = true,
    IndentChars = "    "
}

using (var w = XmlWriter.Create(filename, settings))
{
    // ... Write elements
}

Altri suggerimenti

È necessario creare prima un XmlWriterSettings oggetto che specifica il tuo rientro, poi durante la creazione del XmlWriter, passaggio nell'area di XmlWriterSettings dopo il vostro percorso.

Inoltre, io uso il blocco using di lasciare C # manico smaltimento delle mie risorse in modo che non ho bisogno di preoccuparsi di perdere le risorse su un'eccezione.

{
  XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
  {
    Indent = true,
    IndentChars = "\t",
    NewLineOnAttributes = true
  };

  using (XmlWriter w= XmlWriter.Create("myfile.xml", xmlWriterSettings))
  {
    w.WriteStartDocument();
    w.WriteStartElement("myfile");

    w.WriteElementString("id", id.Text);
    w.WriteElementString("date", dateTimePicker1.Text);
    w.WriteElementString("version", ver.Text);
    w.WriteEndElement();
    w.WriteEndDocument();
  }
}

Controlla le impostazioni di proprietà:

w.Settings.Indent = true;

Edit: non è possibile impostare direttamente:

System.Xml.XmlWriter.Create("path", new System.Xml.XmlWriterSettings())

Impostare la proprietà di formattazione del XmlTextWriter:

TextWriter textWriter;
var xmlTextWriter = new XmlTextWriter(textWriter);
xmlTextWriter.Formatting = Formatting.Indented;

Usa impostazioni come segue:

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.UTF8;
        settings.Indent = true;

        using (MemoryStream memoryStream = new MemoryStream())
        using (XmlWriter xmlDoc = XmlWriter.Create(memoryStream, settings)){
         // logic here..
        }

Questo ti porterà dove si vuole, però, non c'è bisogno di usare MemoryStream, la parte importent è le impostazioni.

Un po 'di versione utilizzando VB.NET XmlWriter più XmlWriterSettings direttamente al file:

Dim oSerializer As New XmlSerializer(GetType(MyType), New XmlRootAttribute("MyRootAttributeName"))
Using oXmlWriter As XmlWriter = XmlWriter.Create("MyFilePath", New XmlWriterSettings With {.Indent = True}) //Default encoding is utf-8
    oSerializer.Serialize(oXmlWriter, oInstanceOfMyType)
    oXmlWriter.Flush()
End Using

Controlla la doco per altre impostazioni e opzioni di sovrascrittura dei file, ma questo è pulito e funziona come previsto in un sacco di situazioni.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top