The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > org.w3c.dom  [30 examples] > Elements  [3 examples]

e531. Getting a DOM Element by Id

    // Obtain an XML document; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", true);
    
    // Retrieve the element using id
    Element element = doc.getElementById("key1");
    
    // Get the element's attribute
    String attrValue = element.getAttribute("value");  // value1
This is the sample input for the example:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map [ <!ELEMENT map (entry*) >
                    <!ELEMENT entry EMPTY >
                    <!ATTLIST entry key   ID    #REQUIRED
                                    value CDATA "mydefault"> ]>
    <map>
        <entry key="key1" value="value1"/>
        <entry key="key2" />
    </map>

 Related Examples
e532. Visiting All the Elements in a DOM Document
e533. Changing the Name of a DOM Element

See also: Adding and Removing Nodes    Element Attributes    Getting Nodes    Text Nodes    XPath   


© 2002 Addison-Wesley.