属性の読み取り
更新 : November 2007
XmlReader クラスは属性を読むための各種のメソッドとプロパティを提供します。属性は要素で最も一般的に見られます。しかし、属性は XML 宣言やドキュメント型ノードでも許可されます。
要素の属性の読み取り
要素ノード上に位置しているときに MoveToAttribute メソッドを使用すると、要素の属性リスト全体にアクセスできます。MoveToAttribute を呼び出した後、Name、NamespaceURI、Prefix などのノード プロパティには、それが属する要素ではなく、その属性のプロパティが反映されます。
次の表では、属性を処理するために特に設計されたメソッドとプロパティについて説明します。
メンバ名 |
説明 |
---|---|
要素上の属性の数を取得します。 |
|
属性の値を取得します。 |
|
現在のノードに属性があるかどうかを示す値を取得します。 |
|
現在のノードが、DTD またはスキーマで定義された既定値から生成された属性であるかどうかを示す値を取得します。 |
|
指定された属性の値を取得します。 |
|
指定された属性に移動します。 |
|
現在の属性ノードを所有する要素に移動します。 |
|
最初の属性に移動します。 |
|
次の属性に移動します。 |
|
属性値を 1 つ以上のテキスト、EntityReference、または EndEntity ノードに解析します。 |
一般の XmlReader のメソッドとプロパティもすべて属性の処理に使用できます。たとえば、XmlReader が属性上に位置した後、Name および Value のプロパティは、その属性の値を反映します。コンテンツの Read メソッドも属性の値を取得するために使用できます。
その他のノード型の属性の読み取り
要素ノード上の属性の処理が最も一般的なシナリオです。属性は XML 宣言とドキュメント型宣言上でも見られます。
メモ : |
---|
XmlReader が処理命令ノード上に位置しているとき、Value プロパティはテキストの内容全体を返します。処理命令ノードのアイテムは属性として扱われません。それらを GetAttribute メソッドまたは MoveToAttribute メソッドで読み取ることはできません。 |
XML 宣言ノード
XML 宣言ノード上に位置したとき、Value プロパティは、バージョン、スタンドアロン、およびエンコーディング情報を単一の文字列として返します。いくつかのリーダーではバージョン、スタンドアロン、およびエンコーディング情報は属性としても公開されます。
メモ : |
---|
Create メソッドにより作成された XmlReader オブジェクト、XmlTextReader クラス、および XmlValidatingReader クラスは、バージョン、スタンドアロン、およびエンコーディング情報を属性として公開します。 |
ドキュメント型ノード
XmlReader がドキュメント型ノード上に位置している場合、GetAttribute メソッドと Item プロパティを使用して SYSTEM および PUBLIC リテラルの値を返すことができます。たとえば、reader.GetAttribute("PUBLIC") は PUBLIC の値を返します。
例
次の例は、AttributeCount プロパティを使用して 1 つの要素上のすべての属性を読み取ります。
' Display all attributes.
If reader.HasAttributes Then
Console.WriteLine("Attributes of <" + reader.Name + ">")
Dim i As Integer
For i = 0 To (reader.AttributeCount - 1)
Console.WriteLine(" {0}", reader(i))
Next i
' Move the reader back to the element node.
reader.MoveToElement()
End If
// Display all attributes.
if (reader.HasAttributes) {
Console.WriteLine("Attributes of <" + reader.Name + ">");
for (int i = 0; i < reader.AttributeCount; i++) {
Console.WriteLine(" {0}", reader[i]);
}
// Move the reader back to the element node.
reader.MoveToElement();
}
次の例は、While ループで MoveToNextAttribute メソッドを使用して 1 つの要素上のすべての属性を読み取ります。
If reader.HasAttributes Then
Console.WriteLine("Attributes of <" + reader.Name + ">")
While reader.MoveToNextAttribute()
Console.WriteLine(" {0}={1}", reader.Name, reader.Value)
End While
' Move the reader back to the element node.
reader.MoveToElement()
End If
if (reader.HasAttributes) {
Console.WriteLine("Attributes of <" + reader.Name + ">");
while (reader.MoveToNextAttribute()) {
Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
}
// Move the reader back to the element node.
reader.MoveToElement();
}
次の例は、名前を指定して属性の値を取得します。
reader.ReadToFollowing("book")
Dim isbn As String = reader.GetAttribute("ISBN")
Console.WriteLine("The ISBN value: " + isbn)
reader.ReadToFollowing("book");
string isbn = reader.GetAttribute("ISBN");
Console.WriteLine("The ISBN value: " + isbn);