Formato de salida XML con XmlTextWriter

Actualización: November 2007

El formato de salida XML de la clase XmlTextWriter se compone de diversas propiedades que, en conjunto, controlan la salida de un documento.

El formato de salida XML de la clase XmlTextWriter se compone de diversas propiedades que, en conjunto, controlan la salida de un documento. Las propiedades de formato de salida son:

  • Formatting

  • IndentChar

  • Indentation

  • QuoteChar

Resultados con formato

Los valores válidos de la propiedad Formatting son None e Indented, siendo None el predeterminado. Cuando se selecciona el valor None, las propiedades IndentChar e Indentation se pasan por alto y no se aplica ningún formato. Si la propiedad Formatting se establece en Indented, la aplicación examina la propiedad Indentation para comprobar cuántos IndentChars se deben escribir en cada nivel de la jerarquía y la propiedad IndentChars especifica qué carácter se debe usar para la sangría. Si el valor de la propiedad Formatting se establece en Indented, el valor predeterminado de la propiedad Indentation indica que hay que escribir dos IndentChars para cada nivel de la jerarquía y el valor predeterminado de IndentChars indica que hay que usar un espacio. Si el valor de la propiedad Formatting se establece en Indented, se aplica sangría a los elementos secundarios de acuerdo con los valores de Indentation e IndentChar. La sangría que aplica la clase XmlTextWriter depende del tipo de nodo. Los nodos afectados por la propiedad Indentation son:

  • DocumentType

  • Elemento

  • Comentario

  • ProcessingInstruction

  • CDATASection

El resto de tipos de nodo no se ven afectados por la propiedad Indentation y no se les aplica sangría.

El subconjunto interno de la definición de tipo de documento (DTD) no tiene sangría ni formato. Sin embargo, se le puede aplicar sangría y formato como se muestra en el ejemplo de código. En el ejemplo se aplica formato al subconjunto interno de la DTD.

String name = "Employees";
String pubid = null;
String sysid = null;
String subset = @"
    <!ELEMENT Employees (Employee)+>
    <!ELEMENT Employee EMPTY>
    <!ATTLIST Employee firstname CDATA #REQUIRED>
    <!ENTITY Company 'Microsoft'>]>
";
XmlTextWriter tw = new XmlTextWriter(Console.Out);
tw.WriteDocType(name, pubid, sysid, subset);

La propiedad QuoteChar determina qué carácter se debe utilizar para poner entre comillas los valores de los atributos. Los valores válidos son:

  • comilla simple (&#39;)

  • comilla doble (&#34;)

El valor predeterminado para QuoteChar es comilla doble (&#34;).

Ejemplo

En el ejemplo siguiente se escribe un fragmento de XML y se establece el valor de la propiedad Formatting en Indented, un nivel de sangría de 4 y el carácter espacio como carácter de sangría (el valor predeterminado).

Option Explicit
Option Strict

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        'Create a writer to write XML to the console.
        Dim writer As XmlTextWriter = Nothing
        writer = New XmlTextWriter(Console.Out)
        
        'Use indentation for readability.
        writer.Formatting = Formatting.Indented
        writer.Indentation = 4
        
        'Write an element (this one is the root).
        writer.WriteStartElement("book")
        
        'Write the title element.
        writer.WriteStartElement("title")
        writer.WriteString("Pride And Prejudice")
        writer.WriteEndElement()
        
        'Write the close tag for the root element.
        writer.WriteEndElement()
        
        'Write the XML to file and close the writer.
        writer.Close()
    End Sub 'Main 
End Class 'Sample
using System;
using System.IO;
using System.Xml;

public class Sample
{
  
  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 4;
        
     //Write an element (this one is the root).
     writer.WriteStartElement("book");

     //Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer.
     writer.Close();  
  }
}

Vea también

Otros recursos

Escribir XML con XmlWriter