XmlElement.GetAttribute 方法

定義

傳回指定屬性的屬性值。

多載

GetAttribute(String)

傳回具有指定名稱之屬性的值。

GetAttribute(String, String)

傳回具有指定區域名稱和命名空間 URI 之屬性的值。

GetAttribute(String)

傳回具有指定名稱之屬性的值。

C#
public virtual string GetAttribute (string name);

參數

name
String

要擷取之屬性的名稱。 這是限定名稱。 它會與符合節點的 Name 屬性比對。

傳回

String

指定的屬性值。 如果找不到相符的屬性,或屬性不具指定或預設值,則會傳回空白字串。

範例

下列範例會檢查項目是否具有指定的屬性。

C#
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    XmlElement root = doc.DocumentElement;

    // Check to see if the element has a genre attribute.
    if (root.HasAttribute("genre")){
      String genre = root.GetAttribute("genre");
      Console.WriteLine(genre);
   }
  }
}

適用於

.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 2.0, 2.1
UWP 10.0

GetAttribute(String, String)

傳回具有指定區域名稱和命名空間 URI 之屬性的值。

C#
public virtual string GetAttribute (string localName, string namespaceURI);
C#
public virtual string GetAttribute (string localName, string? namespaceURI);

參數

localName
String

要擷取的屬性的區域名稱。

namespaceURI
String

要擷取的屬性的命名空間 URI。

傳回

String

指定的屬性值。 如果找不到相符的屬性,或屬性不具指定或預設值,則會傳回空白字串。

適用於

.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 2.0, 2.1
UWP 10.0