次の方法で共有


XmlWriter による XML の書き方

XmlWriter は、XML を書くためのインターフェイスを定義する抽象基本クラスです。XmlWriter には、XML ストリームを生成するための方法として、転送専用、読み取り専用、キャッシュ処理なしの方法が用意されています。この方法は、W3C 勧告『Extensible Markup Language (XML) 1.0 (Second Edition)』(www.w3.org/TR/2000/REC-xml-20001006.html) および『Namespaces in XML』(www.w3.org/TR/REC-xml-names/) に準拠する XML ドキュメントの構築に使用できます。

XmlWriter 用に定義されているメソッドとプロパティの役割の一覧を次に示します。

  • 名前空間をサポートするかどうかを指定します。
  • 適切な形式の XML を書き込みます。
  • base64 と binhex としてバイナリ バイトをエンコードし、エンコード後のテキストを書き出します。
  • 出力を管理します。たとえば、WriteState プロパティを使用して出力の進行を判断するメソッドなどです。
  • 複数のドキュメントを 1 つの出力ストリームに書き込みます。
  • 出力をフラッシュするか、または閉じます。
  • 現在の名前空間プリフィックスである xml:lang または xml:space のスコープを報告します。
  • 有効な名前、修飾された名前、および名前トークンを書き込みます。

XmlWriter がチェックしない項目を示す一覧を次に示します。

  • 無効な要素名文字と属性名文字。
  • 指定されたエンコーディングに適合しない Unicode 文字。指定されたエンコーディングに Unicode 文字が適合しない場合、XmlWriter は Unicode 文字を文字エンティティにエスケープしません。
  • 重複する属性。
  • DOCTYPE パブリック ID またはシステム ID の文字。

XmlWriter では、上に示した 4 項目をチェックしないため、整形式でない XML も作成できます。要素名と属性名に無効な文字が含まれないようにしたり、上記以外の機能が必要だったりする場合は、「カスタマイズされた XML ライタの作成」を参照してください。

XmlWriter を使用する例としては、パイプ (|) 区切りのデータ ファイルのような以前の形式のデータを解析して読み取り、そのデータを XmlTextWriter を使用して XML 形式で書き込む場合などがあります。

入力

data1|data2|data3|data4|data5

このデータを次の形式に変換するとします。

出力

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

ファイル内のデータを個別のデータ トークンにトークン化するためにメソッドが作成されます。この関数を呼び出すたびにデータ要素の 1 つが返されます。このメソッドは 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;
  }

このコードは、各トークンを XML ドキュメントに挿入していき、データ トークンがなくなるまで繰り返します。この処理は Main 関数で行われ、Main 関数は 2 つのコマンド ライン引数を受け取ります。最初の引数はトークンの読み取り元のファイルであり、2 番目は書き込み先のファイルです。コード内のコメントは、行われるアクションを説明しています。

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

XmlWriter とその実装 XmlTextWriter のメソッドは、文字列がパラメータとして使用されているときに、W3C 規則に従って空のコンテンツを出力に書き込みます。つまり次のメソッドでは、値 null または String.Empty が渡された場合は、データ コンテンツのないテキストを書き出し、例外はスローしません。代わりにメソッドは "" を書き込みます。この実装は、WriteProcessingInstruction メソッドで text パラメータに値 null または String.Empty が渡されたときにも適用されます。

  • WriteCData
  • WriteComment
  • WriteProcessingInstruction
  • WriteString

その他のメソッドは、null または String.Empty が渡されたときに例外をスローすることがあります。

XmlWriter には 1 つの実装 XmlTextWriter があります。XmlTextWriter の使い方の詳細については、「XmlTextWriter による適切な形式の XML の作成」を参照してください。XmlWriter のメソッドとプロパティの詳細については、「XmlWriter メンバ」を参照してください。

参照

XmlTextWriter による適切な形式の XML の作成 | XmlTextWriter による XML 出力の書式設定 | XmlTextWriter 内の名前空間機能 | カスタマイズされた XML ライタの作成 | XmlTextWriter クラス | XmlTextWriter メンバ | XmlWriter クラス | XmlWriter メンバ