XmlDocument.GetElementById(String) 方法

定義

會拿到指定 ID 的 。XmlElement

public:
 virtual System::Xml::XmlElement ^ GetElementById(System::String ^ elementId);
public virtual System.Xml.XmlElement GetElementById(string elementId);
abstract member GetElementById : string -> System.Xml.XmlElement
override this.GetElementById : string -> System.Xml.XmlElement
Public Overridable Function GetElementById (elementId As String) As XmlElement

參數

elementId
String

屬性 ID 要匹配。

傳回

若找不到匹配的元素null,則使用 XmlElement ID 相符。

範例

下列範例會使用 GetElementById 方法。


using System;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    XmlDocument doc = new XmlDocument();
    doc.Load("ids.xml");

    //Get the first element with an attribute of type ID and value of A111.
    //This displays the node <Person SSN="A111" Name="Fred"/>.
    XmlElement elem = doc.GetElementById("A111");
    Console.WriteLine( elem.OuterXml );

    //Get the first element with an attribute of type ID and value of A222.
    //This displays the node <Person SSN="A222" Name="Tom"/>.
    elem = doc.GetElementById("A222");
    Console.WriteLine( elem.OuterXml );
  }
}
Option Explicit
Option Strict

Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        Dim doc As New XmlDocument()
        doc.Load("ids.xml")
        
        'Get the first element with an attribute of type ID and value of A111.
        'This displays the node <Person SSN="A111" Name="Fred"/>.
        Dim elem As XmlElement = doc.GetElementById("A111")
        Console.WriteLine(elem.OuterXml)
        
        'Get the first element with an attribute of type ID and value of A222.
        'This displays the node <Person SSN="A222" Name="Tom"/>.
        elem = doc.GetElementById("A222")
        Console.WriteLine(elem.OuterXml)
    End Sub
End Class

範例中使用檔案 ids.xml,作為輸入。

<!DOCTYPE root [
  <!ELEMENT root ANY>
  <!ELEMENT Person ANY>
  <!ELEMENT Customer EMPTY>
  <!ELEMENT Team EMPTY>
  <!ATTLIST Person SSN ID #REQUIRED>
  <!ATTLIST Customer id IDREF #REQUIRED >
  <!ATTLIST Team members IDREFS #REQUIRED>]>
<root>
  <Person SSN='A111' Name='Fred'/>
  <Person SSN='A222' Name='Tom'/>
  <Customer id='A222334444'/>
  <Team members='A222334444 A333445555'/>
</root>

備註

如果文件中有多個元素與 ID 相符,此方法會回傳文件中第一個匹配的元素。

Note

DOM 實作必須包含定義哪些屬性屬於 ID 型別的資訊。 雖然 ID 類型屬性可以在 XSD 架構或 DTD 中定義,但此版本的產品僅支援 DTD 定義的屬性。 名為「ID」的屬性除非在 DTD 中明確定義,否則不屬於 ID 類型。 若實作不確定屬性是否為類型 ID,預期會回傳 null

適用於