XmlTextWriter による XML 出力の書式は、ドキュメントの出力を制御するための複数のプロパティで構成されています。
XmlTextWriter による XML 出力の書式は、ドキュメントの出力を制御するための複数のプロパティで構成されています。 出力の書式設定のプロパティを次に示します。
書式
IndentChar
Indentation
QuoteChar
出力の初期設定
Formatting プロパティの有効な値は None と Indented であり、None が既定値です。 選択された値が None である場合は、IndentChar プロパティと Indentation プロパティは無視され、書式設定は行われません。 Formatting プロパティが Indented に設定されている場合、アプリケーションは Indentation プロパティを調べて、階層内の各レベルについて書き込む IndentChars の数を確認します。IndentChars はインデントに使用する文字を指定します。 Formatting プロパティが Indented に設定されている場合、Indentation の既定の処理では、階層内の各レベルで IndentChars を 2 つ書き込みます。IndentChars の既定値は空白です。 Formatting が Indented に設定されている場合は、Indentation 値と IndentChar 値に応じて子要素がインデントされます。 XmlTextWriter によって実行されるインデントはノード型に依存します。 Indentation プロパティの影響を受けるノードを次に示します。
DocumentType
Element
Comment
ProcessingInstruction
CDATASection
これ以外のすべてのノード型は Indentation プロパティの影響を受けないため、インデントは実行されません。
ドキュメント型定義 (DTD) の内部サブセットでは、インデントも書式設定も行われません。 ただし、インデントや書式設定を行うこともでき、それを示すコード サンプルを次に示します。 このコード サンプルでは、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);
QuoteChar プロパティを使用して、属性値を囲む引用符文字を決定します。 有効な文字を次に示します。
一重引用符 (')
二重引用符 (")
QuoteChar の既定値は二重引用符 (") です。
例
XML フラグメントを書く例を次に示します。Formatting プロパティを Indented に、インデント レベルを 4 に、インデント文字を空白 (既定値) にそれぞれ設定します。
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();
}
}