XmlDocument.GetElementById Method

Gets the XmlElement with the specified ID.

Namespace:  System.Xml
Assembly:  System.Xml (in System.Xml.dll)

public virtual XmlElement GetElementById(
	string elementId
)

Parameters

elementId
Type: System.String

The attribute ID to match.

Return Value

Type: System.Xml.XmlElement
The XmlElement with the matching ID or null if no matching element is found.

If the document has multiple elements with the matching ID, this method returns the first matching element in the document.

NoteNote

The DOM implementation must have information which defines which attributes are of type ID. Although attributes of type ID can be defined in either XSD schemas or DTDs, this version of the product only supports those defined in DTDs. Attributes with the name "ID" are not of type ID unless so defined in the DTD. Implementations where it is unknown whether the attributes are of type ID are expected to return null.

The following example uses the GetElementById method.


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 ); 

  }
}

The example uses the file, ids.xml, as input.


<!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='A111'/>
  <Person SSN='A222' Name='Tom'/>
  <Customer id='A111'/>
  <Customer id='A222334444'/>
  <Team members='A222334444 A333445555'/>
</root>

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft