visual texto studio organizar ordenar net lineas indentación identar formato dar como codigo code asp alinear c# xml xmlwriter

c# - texto - ordenar lineas de codigo visual studio code



Sangría y comando de nueva línea para XMLwriter en C# (6)

Compruebe la propiedad de configuración:

w.Settings.Indent = true;

Editar: No puedes configurarlo directamente:

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

Estoy escribiendo algunos datos en un archivo XML ... pero cuando lo abro, todos los valores están en una sola línea ... ¿cómo se puede escribir en formato legible? Es decir, cada nodo en una nueva línea y sangría.

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


Establezca la propiedad de formato de XmlTextWriter:

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


Primero debe crear un objeto XmlWriterSettings que especifique su sangría, luego, al crear su XmlWriter, pase el XmlWriterSettings después de su ruta.

Además, uso el bloque de using para permitir que C # maneje la disposición de mis recursos para que no tenga que preocuparme por perder ningún recurso en una excepción.

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


Una pequeña versión de VB.NET que usa XmlWriter más XmlWriterSettings directamente al archivo:

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

Verifique el doco para otras configuraciones y opciones de sobrescritura de archivos, pero esto está limpio y funciona como se espera en muchas situaciones.


Use un XmlTextWriter lugar de XmlWriter y luego establezca las propiedades de Indentation .

Ejemplo

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 }

Después del comentario de @jumbo, esto también podría implementarse como en .NET 2.

var filename = "MyFile.xml"; var settings = new XmlWriterSettings() { Indent = true, IndentChars = " " } using (var w = XmlWriter.Create(filename, settings)) { // ... Write elements }


Utilice la configuración como sigue:

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.. }

Esto lo llevará a donde quiera, sin embargo, no tiene que usar MemoryStream, la parte importante es la configuración.