XmlReader.GetAttribute 方法

定義

在衍生類別中覆寫時,取得屬性值。

多載

GetAttribute(String, String)

在衍生類別中覆寫時,取得具有指定 LocalNameNamespaceURI 的屬性值。

GetAttribute(Int32)

在衍生類別中覆寫時,取得具有指定索引的屬性值。

GetAttribute(String)

在衍生類別中覆寫時,取得具有指定 Name 的屬性值。

GetAttribute(String, String)

在衍生類別中覆寫時,取得具有指定 LocalNameNamespaceURI 的屬性值。

C#
public abstract string GetAttribute (string name, string namespaceURI);
C#
public abstract string? GetAttribute (string name, string? namespaceURI);

參數

name
String

屬性的本機名稱。

namespaceURI
String

屬性的命名空間 URI。

傳回

String

指定的屬性值。 如果找不到該屬性或其值為 String.Empty,則傳回 null。 這個方法不會移動讀取器。

例外狀況

namenull

在先前的非同步作業完成前呼叫了 XmlReader 方法。 在此情況下,會擲回 InvalidOperationException 與「非同步作業已經在進行中」的訊息。

備註

下列 XML 包含特定命名空間中的屬性:

XML
<test xmlns:dt="urn:datatypes" dt:type="int"/>

您可以使用一個引數 (前置詞和區功能變數名稱稱) 或兩個引數來查閱 dt:type 屬性, (本機名稱和命名空間 URI) :

C#
String dt = reader.GetAttribute("dt:type");
String dt2 = reader.GetAttribute("type","urn:datatypes");

若要查閱 xmlns:dt 屬性,請使用下列其中一個引數:

C#
String dt3 = reader.GetAttribute("xmlns:dt");
String dt4 = reader.GetAttribute("dt",http://www.w3.org/2000/xmlns/);

您也可以使用 Prefix 屬性取得這項資訊。

適用於

.NET 7 及其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

GetAttribute(Int32)

在衍生類別中覆寫時,取得具有指定索引的屬性值。

C#
public abstract string GetAttribute (int i);

參數

i
Int32

屬性的索引。 此索引是以零為起始。 (第一個屬性的索引為 0。)

傳回

String

指定的屬性值。 這個方法不會移動讀取器。

例外狀況

i 超出範圍。 它必須是非負值,而且小於屬性集合的大小。

在先前的非同步作業完成前呼叫了 XmlReader 方法。 在此情況下,會擲回 InvalidOperationException 與「非同步作業已經在進行中」的訊息。

範例

下列範例會取得第三個屬性的值。

C#
reader.ReadToFollowing("book");
string isbn = reader.GetAttribute(2);

適用於

.NET 7 及其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

GetAttribute(String)

在衍生類別中覆寫時,取得具有指定 Name 的屬性值。

C#
public abstract string GetAttribute (string name);
C#
public abstract string? GetAttribute (string name);

參數

name
String

屬性的限定名稱 (Qualified Name)。

傳回

String

指定的屬性值。 如果找不到該屬性或其值為 String.Empty,則傳回 null

例外狀況

namenull

在先前的非同步作業完成前呼叫了 XmlReader 方法。 在此情況下,會擲回 InvalidOperationException 與「非同步作業已經在進行中」的訊息。

範例

下列範例會取得 ISBN 屬性的值。

C#
reader.ReadToFollowing("book");
string isbn = reader.GetAttribute("ISBN");
Console.WriteLine("The ISBN value: " + isbn);

備註

這個方法不會移動讀取器。

如果讀取器位於 DocumentType 節點上,則這個方法可用來取得 PUBLIC 和 SYSTEM 常值,例如 reader.GetAttribute("PUBLIC")

適用於

.NET 7 及其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0