HtmlElement.GetAttribute(String) 方法

定義

擷取此項目上具名屬性的值。

public:
 System::String ^ GetAttribute(System::String ^ attributeName);
public string GetAttribute (string attributeName);
member this.GetAttribute : string -> string
Public Function GetAttribute (attributeName As String) As String

參數

attributeName
String

屬性的名稱。 這個引數不區分大小寫。

傳回

項目上這個屬性的值,為 String 值。 如果指定的屬性不存在這個項目上,則會傳回空字串。

範例

下列程式碼範例會擷取 HTML 檔案內的所有 META 標記,使用 GetAttribute 來尋找 META 名稱 Description 為 的標記。 此範例要求您的應用程式有 WebBrowser 名為 的 WebBrowser1 控制項。

private void DisplayMetaDescription()
{
    if (webBrowser1.Document != null)
    {
        HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("META");
        foreach (HtmlElement elem in elems)
        {
            String nameStr = elem.GetAttribute("name");
            if (nameStr != null && nameStr.Length != 0)
            {
                String contentStr = elem.GetAttribute("content");
                MessageBox.Show("Document: " + webBrowser1.Url.ToString() + "\nDescription: " + contentStr);
            }
        }
    }
}
Private Sub DisplayMetaDescription()
    If (WebBrowser1.Document IsNot Nothing) Then
        Dim Elems As HtmlElementCollection 
        Dim WebOC as WebBrowser = WebBrowser1

    Elems = WebOC.Document.GetElementsByTagName("META")

        For Each elem As HtmlElement In Elems
            Dim NameStr As String = elem.GetAttribute("name")

            If ((NameStr IsNot Nothing) And (NameStr.Length <> 0)) Then
                If NameStr.ToLower().Equals("description") Then
                    Dim ContentStr As String = elem.GetAttribute("content")
                    MessageBox.Show("Document: " & WebOC.Url.ToString() & vbCrLf & "Description: " & ContentStr)
                End If
            End If
        Next
    End If
End Sub

備註

HTML 中的屬性是該專案的任何有效名稱/值組。 HtmlElement只會公開所有元素通用的屬性,並排除僅適用于特定專案類型的屬性;SRC是標記的 IMG 預先定義屬性,例如,而不是標記。 DIV 使用 GetAttributeSetAttribute 操作 Managed 檔物件模型上未公開的屬性, (DOM) 。

GetAttributeSetAttribute 不區分大小寫。

適用於

另請參閱