Scrittura dell'XML con XmlWriter

XmlWriter è una classe astratta di base che consente di definire un'interfaccia per scrivere l'XML. XmlWriter fornisce un modo forward-only, di sola lettura, non memorizzato nella cache per la generazione di flussi XML, che agevolano la creazione di documenti XML conformi alle raccomandazioni del W3C, Extensible Markup Language (XML) 1.0 (Seconda edizione), (www.w3.org/TR/2000/REC-xml-20001006.html) e Namespaces in XML (www.w3.org/TR/REC-xml-names/).

Nell'elenco seguente sono descitti i metodi e le proprietà di XmlWriter definiti per:

  • Specificare se supportare gli spazi dei nomi.
  • Scrivere l'XML in formato corretto.
  • Codificare i byte binari come base64 e binhex e riportare il testo risultante.
  • Gestire l'output, compresi i metodi per determinare lo stato di avanzamento dell'output, con la proprietà WriteState.
  • Scrivere più documenti in un unico flusso di output.
  • Svuotare o chiudere l'output.
  • Indicare il prefisso dello spazio dei nomi corrente, l'area di attività xml:lang o xml:space.
  • Scrivere nomi validi, qualificati e token del nome.

Nell'elenco che segue sono identificate le aree non interessate dalla verifica di XmlWriter:

  • Caratteri non validi dei nomi di elementi e attributi.
  • Caratteri Unicode che non rientrano nella codifica specificata. Se i caratteri Unicode non rientrano nella codifica specificata, XmlWriter non esegue l'escape dei caratteri Unicode in entità di carattere.
  • Attributi duplicati.
  • Caratteri nell'identificatore pubblico DOCTYPE o nell'identificatore di sistema.

Poiché XmlWriter non controlla questi quattro elementi, è possibile creare codice XML in formato non valido. Se occorre essere sicuri che i nomi di elemento e di attributi includano solo caratteri validi o che dispongano di altre caratteristiche sopra descritte, vedere Creazione di un writer XML personalizzato.

Uno scenario in cui potrebbe essere utilizzato XmlWriter è per la lettura di dati preesistenti, come l'analisi con un parser di un file di dati delimitato da un carattere pipe (|) e la scrittura dei dati in un formato XML utilizzando XmlTextWriter.

Input

data1|data2|data3|data4|data5

e si desidera trasformarlo in:

Output

<data>
      <item> data1 </item>
      <item> data2 </item>
      <item> data3 </item>
      <item> data4 </item>
      <item> data5 </item>
</data>

Viene creato un metodo per rappresentare i dati del file in singoli token di dati. Con ogni chiamata a questa funzione viene restituito uno degli elementi dei dati. Il metodo accetta come input uno StreamReader.

Public Shared Function NextToken(ByVal stream As StreamReader) As String
    Dim temp As Integer = stream.Read()
    Dim t1 As String = ""
    While temp <> -1 And ChrW(temp) <> "|"
        t1 += ChrW(temp)
        temp = stream.Read()
    End While
    Return t1
End Function 'NextToken
[C#]
public static String NextToken(StreamReader stream)
  {
      int temp = stream.Read();
      String t1 = "";
      while(temp != -1 && temp != (int)'|')
            {
                  t1 += (char)temp;
                  temp = stream.Read();
            }
      return t1;
  }

Il codice esegue uno scorrimento quando non vi sono più token di dati e ogni token viene inserito in un documento XML. Questa operazione viene eseguita nella funzione Main, che utilizza due argomenti della riga di comando: il primo è il file dal quale leggere, il secondo è il file nel quale scrivere. Viene fornita una descrizione delle azioni in corso tramite commenti all'interno del codice.

Imports System
Imports System.IO
Imports System.Xml
Imports Microsoft.VisualBasic.Strings

Namespace TextFiletoXml
    Class TextFiletoXml
        Public Shared file As String
        Public Shared stream As StreamReader
        Public Shared xwriter As XmlTextWriter
        Public Shared val As String

        Public Shared Function NextToken(ByVal stream As StreamReader) As String
            Dim temp As Integer = stream.Read()
            Dim t1 As String = ""
            While temp <> -1 And ChrW(temp) <> "|"
                t1 += ChrW(temp)
                temp = stream.Read()
            End While
            Return t1
        End Function 'NextToken

    Public Overloads Shared Sub Main()
        dim args() As String=System.Environment.GetCommandLineArgs()
        file = args(1)

        'Create a new stream representing the file we are reading from.
        stream = New StreamReader(file, True)

        'Create a new XmlTextWriter.
        xwriter = New XmlTextWriter(args(2), System.Text.Encoding.UTF8)

        'Write the beginning of the document including the 
        'document declaration. Standalone is true. 
        xwriter.WriteStartDocument(True)

        'Write the beginning of the "data" element. This is 
        'the opening tag to our data. 
        xwriter.WriteStartElement("data", "www.alpineskihouse.com")

        'Get the first data element from the file.
        val = NextToken(stream)

        'Create a new element with each data token from the stream.
        While val <> ""
            xwriter.WriteElementString("item", "www.alpineskihouse.com", val)
            val = NextToken(stream)
        End While     
        xwriter.WriteEndElement()  'End the "data" element.
        xwriter.WriteEndDocument() 'End the document

        'Flush the XML document to the underlying stream and
        'close the underlying stream. The data will not be written out 
        'to the stream until either the Flush() method is called or 
        'the Close() method is called.
        xwriter.Close()
    End Sub 'Main
    End Class 'TextFiletoXml
End Namespace 'TextFiletoXml
[C#]
using System;
using System.IO;
using System.Xml;

namespace TextFiletoXml
{

    class TextFiletoXml
    {
        public static String file;
        public static StreamReader stream;
        public static XmlTextWriter xwriter;
        public static String val;
        public static String NextToken(StreamReader stream)
        {
            int temp = stream.Read();
            String t1 = "";
            while(temp != -1 && temp != (int)'|')
            {
                t1 += (char)temp;
                temp = stream.Read();
            }

            return t1;

        }

        public static void Main(string[] args)
        {
            file = args[0];

            //Create a new stream representing the file we are 
            //reading from.
            stream = new StreamReader(file, true);

            //Create a new XmlTextWriter.
           xwriter = new XmlTextWriter(args[1],System.Text.Encoding.UTF8);
            //Write the beginning of the document including the 
            //document declaration. Standalone is true. 

            xwriter.WriteStartDocument(true);

            //Write the beginning of the "data" element. This is 
            //the opening tag to our data 

            xwriter.WriteStartElement("data","www.alpineskihouse.com");

            // Get the first data element from the file.
            val = NextToken(stream);

            //create a new element with each data token from //the stream.
            while(val != "")
            {

               xwriter.WriteElementString("item","www.alpineskihouse.com", val);
                val = NextToken(stream);
            }
            //End the "data" element.
            xwriter.WriteEndElement();

            //End the document
            xwriter.WriteEndDocument();

            //Flush the xml document to the underlying stream and
            //close the underlying stream. The data will not be
            //written out to the stream until either the Flush()
            //method is called or the Close() method is called.
            xwriter.Close();
        }
    }
}

Con i metodi di XmlWriter e la sua implementazione, XmlTextWriter, è possibile riportare un contenuto vuoto nell'output quando viene utilizzata una stringa come parametro, in conformità con le regole del W3C. Questo significa che per i metodi seguenti, se viene fornito il valore null o String.Empty, il testo viene riportato dai metodi senza contenuto di dati e non viene generata un'eccezione. Verrà invece scritto "". Questa implementazione vale per il metodo WriteProcessingInstruction quando il valore null o String.Empty viene passato al parametro text.

  • WriteCData
  • WriteComment
  • WriteProcessingInstruction
  • WriteString

Altri metodi potrebbero generare un'eccezione se viene passato un valore null o String.Empty.

L'unica implementazione di XmlWriter è XmlTextWriter. Per ulteriori informazioni sull'utilizzo di XmlTextWriter, vedere Creazione di XML in formato corretto con XmlTextWriter. Per ulteriori informazioni sui metodi e sulle proprietà di XmlWriter, vedere Membri XmlWriter.

Vedere anche

Creazione di XML in formato corretto con XmlTextWriter | Formattazione dell'output XML con XmlTextWriter | Funzioni dello spazio dei nomi all'interno di XmlTextWriter | Creazione di un writer XML personalizzato | Classe XmlTextWriter | Membri XmlTextWriter | Classe XmlWriter | Membri XmlWriter