C# - Creare xml con indentazione e caratteri a capo
Solução
Per aggiungere l'indentazione e la fine riga ad un xml ecco il seguente codice dove c'è una funzione a cui viene passato il path del file, l'oggetto da serializzare, attraverso degli attributi assegnati all'oggetto e alle sue proprietà:
private void SaveXml(string path, object o)
{
try
{
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
var xml = new XmlSerializer(o.GetType());
// Create the file.
//using (var fs = File.Create(path))
using (var fs = XmlWriter.Create(path, new XmlWriterSettings() { Indent = true }))
{
var ns = new XmlSerializerNamespaces();
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
ns.Add("xhtml", "http://www.w3.org/1999/xhtml");
ns.Add("xhtml", "http://www.w3.org/1999/xhtml");
xml.Serialize(fs, o, ns);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Durante la chiamata alla funzione XmlWriter.Create passeremo XmlWriterSettings dove definiremo di impostare l'indentazione tramite la proprietà Indent a true.Licenciado em: CC-BY-SA com atribuição