Code Examples from Chapter 21, DOM Reference

The contents of this page were extracted from the source file for Chapter 21 by a quick and dirty Microsoft Word VBScript macro. The formatting isn't great, and it may not be complete.

The <h2> level headings give the current interface, the <h3> level headings give the current attribute or method. By searching for the attribute or method you want you should be able to find the sample code in question.

Once again, sorry about the quality of the file, but if it came down to getting your hands on the code in electronic (but imperfect) form, or not getting the code at all, I assume you prefer the latter.

If you want more information on how I extracted this stuff, or would like to volunteer to clean this file up a little bit (I can dream, can't I :-), please feel free to email me.

W. Scott Means, January 28, 2001

Attr

    Attr attrName = elem.getAttributeNode("size");

name

String getName();
Attr attr;
    
    for (int i = 0; i < elem.getAttributes().getLength(); i++) {
        // temporarily alias the attribute
        attr = (Attr)elem.getAttributes().item(i);
        System.out.println(attr.getName());
    }

ownerElement()

Element getOwnerElement();

specified

boolean getSpecified();
    for (int i = 0; i < elem.getAttributes().getLength(); i++) {
        // temporarily alias the attribute
        attr = (Attr)elem.getAttributes().item(i);

        // only show attributes that were explicitly included in the XML source file
        // (i.e. ignore default attributes from the DTD.)
        if (attr.getSpecified()) {
            System.out.println(attr.getName());
        }
    }
String getValue();
public void setValue(String value);
Attr attr;

    for (int i = 0; i < elem.getAttributes().getLength(); i++) {
        attr = (Attr)elem.getAttributes().item(i);
        attr.setValue(attr.getValue().toLowerCase());
    }
try {
        FileInputStream fis = new FileInputStream("phone_list.xml");
        StringBuffer sb = new StringBuffer();

        // read the XML source file into memory
        int ch;
        while ((ch = fis.read()) != -1) {
            sb.append((char)ch);
        }
        
        // now, create a CDATASection object to contain it within
        // an element of our document using the CDATA facility
        CDATASection ndCDATA = doc.createCDATASection(sb.toString());
    } catch (IOException e) {
    ...

CharacterData

    Text ndText = doc.createTextNode("The truth is out there.");

    // cast it to the CharacterData interface
    CharacterData ndCD = (CharacterData)ndText;

data

CharacterData ndCD = (CharacterData)doc.createTextNode("Unquoted text.");
    ...
    ndCD.setData('\"' + ndCD.getData() + '\"');
String getData() throws DOMException;
public void setData(String data) throws DOMException;

length

unsigned long getLength();
    CharacterData ndCD = (CharacterData)doc.createTextNode("This string has 30 characters.");

	System.out.println("The string \'" + ndCD.getData() + "\' has " 
            + Long.toString(ndCD.getLength()) + " characters.");

appendData (arg)

public void appendData(String arg) throws DOMException;
    CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is ");

    // flip a coin
    ndCD.appendData((Math.random() < 0.5) ? "out there." : "in here.");

    System.out.println(ndCD.getData());
public void deleteData(unsigned long offset, unsigned long count) throws DOMException;
    CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is not out there.");

    // change of heart
    ndCD.deleteData(12, 4);

    System.out.println(ndCD.getData());
public void insertData(unsigned long offset, String arg) throws DOMException;
boolean fCynical = true;

    // create a new Text object, and reference the CharacterData interface
    CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is out there.");

    ...

    // check for cynicism
    if (fCynical) {
        ndCD.insertData(12, " not");
    }

    System.out.println(ndCD.getData());
cdNode.deleteData(offset, count);
    cdNode.insertData(offset, arg);
public void replaceData(unsigned long offset, unsigned long count, String arg) throws DOMException;
    CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is not out there.");

    // replace the truth
    String strFind = "truth";
    String strReplace = "dog";
    
    ndCD.replaceData(ndCD.getData().indexOf(strFind), strFind.length(), strReplace);

    System.out.println(ndCD.getData());
public String substringData(unsigned long offset, unsigned long count) throws DOMException;
    CharacterData ndCD = (CharacterData)doc.createTextNode("The truth is out there.");

    // we only want the "truth"
    String strTruth = ndCD.substringData(4, 5);

    System.out.println("The substring is '" + strTruth + '\'');
    Comment ndComment = doc.createComment("Document was parsed by DOM utility.");

    // and add it to the document
    doc.appendChild(ndComment);

Document

doctype

DocumentType getDoctype();
    DocumentType docType = docIn.getDoctype();

    if (docType == null) {
        System.out.println("warning: no DTD provided");
    }
Element getDocumentElement();
Element elRoot = docIn.getDocumentElement();
    System.out.println("This is a '" + elRoot.getTagName() + "' document.");
DOMImplementation getImplementation();
    DOMImplementation di = doc.getImplementation();
    if (!di.hasFeature("XML", "1.0")) {
        return false;
    }

createAttribute (name)

public Attr createAttribute(String name) throws DOMException;
    EntityReference er = doc.createEntityReference("name_entity");
    
    // must create an Attribute object to include an explicit
    // entity reference
    Attr attr = doc.createAttribute("name");
    
    // append the entity reference
    attr.appendChild(er);
public Attr createAttributeNS(String namespaceURI, String qualifiedName)
    throws DOMException;

createCDATASection (data)

public CDATASection createCDATASection(String data) throws DOMException;
    CDATASection cds = doc.createCDATASection("
This is sample text.
");
public Comment createComment(String data);
    StringBuffer sb = new StringBuffer();
    Date dtNow = new Date();

    sb.append("\tModified " + dtNow.toString() + '\n');

    Comment cmt = doc.createComment(sb.toString());
public DocumentFragment createDocumentFragment();

createElement (tagName)

public Element createElement(String tagName) throws DOMException;
    Element elOut = doc.createElement("my_tag");
public Element createElementNS(String namespaceURI, String qualifiedName)
    throws DOMException;

createEntityReference (name)

public EntityReference createEntityReference(String name) throws DOMException;
    EntityReference er = doc.createEntityReference("name_entity");
public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException;
    ProcessingInstruction pi = doc.createProcessingInstruction("my_app",
            "action=\"save\"");
public Text createTextNode(String data);
    Text txtDesc = doc.createTextNode("Character data contents for a new Element.");
public Element getElementById(String elementId);

getElementsByTagName (tagName)

public NodeList getElementsByTagName(String tagName);
    NodeList nl = doc.getElementsByTagName("phone_number");
public NodeList getElementsByTagNameNS(String namespaceURI, String localName);

hasAttribute (name)(

public boolean hasAttribute(String name);

hasAttributeNS (namespaceURI, localName)(

public boolean hasAttributeNS(String namespaceURI, String localName);

importNode (importedNode, deep) (

public Node importNode(Node importedNode, boolean deep)
    throws DOMException;

DocumentFragment

DocumentFragment dfNorm = doc.createDocumentFragment();

    sample.xml before DocumentFragment copy operation
    
        
            
            
        
        
        
    


    DocumentFragment object on clipboard.
    
        
        
    


    sample.xml after DocumentFragment copy operation
    
        
            
            
        
        
            
            
        
    

DocumentType

// get document type information
    DocumentType dtDoc = doc.getDoctype();

entities

NamedNodeMap getEntities();
    NamedNodeMap nnm = doc.getDoctype().getEntities();

    Entity ndEnt;
    for (int i = 0; i < nnm.getLength(); i++) {
        ndEnt = (Entity)nnm.item(i);

        System.out.println(ndEnt.getNodeName());

        if (ndEnt.getPublicId() != null) {
            System.out.println("\tPublic Identifier: " + ndEnt.getPublicId());
        }

        if (ndEnt.getSystemId() != null) {
            System.out.println("\tSystem Identifier: " + ndEnt.getSystemId());
        }

        if (ndEnt.getNotationName() != null) {
            System.out.println("\tNotation Name: " + ndEnt.getNotationName());
        }
    }
String getInternalSubset();

name

String getName();
DocumentType dtDoc = doc.getDoctype();

        System.out.println("This is a " + dtDoc.getName() + " document.");
NamedNodeMap getNotations();
    NamedNodeMap nnm = doc.getDoctype().getNotations();
    Notation ndNotation;
    for (int i = 0; i < nnm.getLength(); i++) {
        ndNotation = (Notation)nnm.item(i);

        System.out.println(ndNotation.getNodeName());
        if (ndNotation.getPublicId() != null) {
            System.out.println("\tPublic Identifier: " + ndNotation.getPublicId());
        }
        if (ndNotation.getSystemId() != null) {
            System.out.println("\tSystem Identifier: " + ndNotation.getSystemId());
        }
    }
String getPublicId();

systemId

String getSystemId();

DOMException

INDEX_SIZE_ERR [value: 1]

public static final short INDEX_SIZE_ERR = 1;

DOMSTRING_SIZE_ERR [value: 2]

public static final short DOMSTRING_SIZE_ERR = 2;

HIERARCHY_REQUEST_ERR [value: 3 ]

public static final short HIERARCHY_REQUEST_ERR = 3;

WRONG_DOCUMENT_ERR [value: 4 ]

public static final short WRONG_DOCUMENT_ERR = 4;

INVALID_CHARACTER_ERR [value: 5 ]

public static final short INVALID_CHARACTER_ERR = 5;

NO_DATA_ALLOWED_ERR [value: 6 ]

public static final short NO_DATA_ALLOWED_ERR = 6;

NO_MODIFICATION_ALLOWED_ERR [value: 7 ]

public static final short NO_MODIFICATION_ALLOWED_ERR = 7;

NOT_FOUND_ERR [value: 8 ]

public static final short NOT_FOUND_ERR = 8;

NOT_SUPPORTED_ERR [value: 9 ]

public static final short NOT_SUPPORTED_ERR = 9;

INUSE_ATTRIBUTE_ERR [value: 10 ]

public static final short INUSE_ATTRIBUTE_ERR = 10;

INVALID_ACCESS_ERR [value: 15 ](

public static final short INVALID_ACCESS_ERR = 15;

INVALID_MODIFICATION_ERR [value: 13 ](

public static final short INVALID_MODIFICATION_ERR = 13;

INVALID_STATE_ERR [value: 11 ](

public static final short INVALID_STATE_ERR = 11;

NAMESPACE_ERR [value: 14 ](

public static final short NAMESPACE_ERR = 14;

SYNTAX_ERR [value: 12 ](

public static final short SYNTAX_ERR = 12;

DOMImplementation

import com.w3c.dom.DOMImplementation;
...
DOMImplementation di = doc.getImplementation();
// make sure that DOM Level 1 XML is supported
if (!di.hasFeature("XML", "1.0")) {
    return null;
}

createDocument (namespaceURI, qualifiedName, doctype)(

public Document createDocument(String namespaceURI,
    String qualifiedName, DocumentType doctype) throws DOMException;

createDocumentType (qualifiedName, publicId, systemId)(

public DocumentType createDocumentType(String qualifiedName,
  String publicId, String systemId) throws DOMException;

hasFeature ( feature, version )

public boolean hasFeature(String feature, String version);
if (!di.hasFeature("XML", "1.0")) {
    return null;
}

Element

Element elem = doc.getDocumentElement();

tagName

String getTagName();
// show the name of the root element tag
Element elem = doc.getDocumentElement();
System.out.println("This is a " + elem.getTagName() + " document.");

getAttribute (name)

public String getAttribute(String name);
Element elem = doc.getDocumentElement();

Java example:      if (elem.getAttribute("name") == "") {
        System.out.println("warning: " + elem.getTagName() + " element: no name attribute");
    }
public String getAttributeNS(String namespaceURI, String localName);

getAttributeNode (name)

public Attr getAttributeNode(String name);
    Attr attr;

    if ((attr = elem.getAttributeNode("id")) == null) {
        System.out.println("warning: element " + elem.getTagName() + ": no id attribute provided.");
    }
public Attr getAttributeNodeNS(String namespaceURI, String localName);

getElementsByTagName (name)

public NodeList getElementsByTagName(String name);
    Element elem = doc.getDocumentElement();
    NodeList nlAddrs = elem.getElementsByTagName("address");
public NodeList getElementsByTagNameNS(String namespaceURI, String localName);

hasAttribute (name) (

public boolean hasAttribute(String name);

hasAttributeNS (namespaceURI, localName) (

public boolean hasAttribute(String namespaceURI, String localName);

normalize ( )


    
        This text 
        is broken.
    


    
        This text is broken.
    

public void normalize();
    elem.normalize();
public void removeAttribute(String name) throws DOMException;
...
    elem.removeAttribute("id");
    ...
public void removeAttributeNS(String namespaceURI, String localName)
     throws DOMException;
public Attr removeAttributeNode(Attr oldAttr) throws DOMException;
Attr attr;

        if ((attr = elem.getAttributeNode("temp")) != null) {
        // remove it
        elem.removeAttributeNode(attr);
    }
public void setAttribute(String name, String value) throws DOMException;
    if (elem.getAttribute("name") == "") {
        // oh well, set a reasonable default
        elem.setAttribute("name", elem.getTagName());
    }
public void setAttributeNS(String namespaceURI, String qualifiedName,
    String value) throws DOMException;

setAttributeNode (newAttr)

public Attr setAttributeNode(Attr newAttr) throws DOMException;
    Attr attr;

    if ((attr = elem.getAttributeNode("id")) == null) {
        // add a default, unique id
        attr = doc.createAttribute("id");

        attr.setValue(MyClass.makeUniqueID(elem));

        // continue processing
    }
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException;

Entity

    Entity ndEnt = (Entity)doc.getDoctype().getEntities().getNamedItem("my_entity");

notationName

String getNotationName();
    boolean fParsedEnt = ndEnt.getNotationName() == null;
String getPublicId();
    Entity ndEnt = (Entity)doc.getDoctype().getEntities().getNamedItem("my_entity");
    
    // if my_entity type was found and there is a system ID (URL)...
    if (ndEnt != null && ndEnt.getPublicId() != null) {
        try {
            // ...get the URL protocol
            URL urlSys = new URL(ndEnt.getPublicId());
            System.out.println("Entity " + ndEnt.getNodeName() + ": protocol " + urlSys.getProtocol());
        } catch (MalformedURLException e) {
        }
    }
String getSystemId();
Entity ndEnt = (Entity)doc.getDoctype().getEntities().getNamedItem("my_entity");

    String strURL = ndEnt.getPublicId();
    
    // if can't find the public URL
    if (strURL == null) {
        // find the system URL
        strURL = ndEnt.getSystemId();
    }
EntityReference ndER = doc.createEntityReference("my_entity");

NamedNodeMap

NamedNodeMap nnm = elem.getAttributes();
unsigned long getLength();
    for (int i = 0; i < nnm.getLength(); i++) {
        ...
    }

getNamedItem (name)

public Node getNamedItem(String name);
    // in this map, and add it if necessary
    if (nnm.getNamedItem("id") == null) {
        // get the document
        Document doc = elem.getOwnerDocument();
        // create a new attribute Node
        Attr attrID = doc.createAttribute("id");

        // set the attribute value
        attrID.appendChild(doc.createTextNode(makeUniqueID(elem)));

        // ... and add it to the NamedNodeMap
        nnm.setNamedItem(attrID);
    }
public Node getNamedItemNS(String namespaceURI, String localName);

item (index)

public Node item(unsigned long index);
    if (nnm.getLength() > 0) {
        nnm.removeNamedItem(nnm.item(nnm.getLength()-1).getNodeName());
    }
public Node removeNamedItem(String name) throws DOMException;
NamedNodeMap nnm = elem.getAttributes();


    if (nnm.removeNamedItem("id") == null) {
        System.err.println("no ID attribute found");
    }
public Node removeNamedItemNS(String namespaceURI, String localName);

setNamedItem (arg)

public Node setNamedItem(Node arg) throws DOMException;
    // in this map, and add it if necessary
    if (nnm.getNamedItem("id") == null) {
        // get the document
        Document doc = elem.getOwnerDocument();
        // create a new attribute Node
        Attr attrID = doc.createAttribute("id");

        // set the attribute value
        attrID.appendChild(doc.createTextNode(makeUniqueID(elem)));

        // ... and add it to the NamedNodeMap
        nnm.setNamedItem(attrID);
    }
public Node setNamedItemNS(Node arg) throws DOMException;

Node

attributes

NamedNodeMap getAttributes();
NamedNodeMap nnm = doc.getDocumentElement().getAttributes();

    if (nnm != null) {

        for (int i = 0; i < nnm.getLength(); i++) {
            // print the attribute and value
            System.out.println(nnm.item(i).getNodeName() + " = \"" + nnm.item(i).getNodeValue() + "\"");
        }
    }
NodeList getChildNodes();
    NodeList nlChildren = elem.getChildNodes();
    Node ndChild;

    for (int iNode = 0; iNode < nlChildren.getLength(); iNode++) {
        ndChild = nlChildren.item(iNode);

        if (ndChild.getNodeType() == Node.TEXT_NODE) {
            System.out.println(ndChild.getNodeValue());
        }
    }
Node getFirstChild();
    for (Node nd = ndDump.getFirstChild(); nd != null; nd = nd.getNextSibling()) {
        if (nd.getNodeValue() != null) {
            System.out.println(nd.getNodeValue());
        }
    }
Node getLastChild();
    for (Node nd = ndDump.getLastChild(); nd != null; nd = nd.getPreviousSibling()) {
        if (nd.getNodeValue() != null) {
            System.out.println(nd.getNodeValue());
        }
    }
public String getLocalName();

namespaceURI (

public String getNamespaceURI();

nextSibling

Node getNextSibling();
    for (Node nd = ndDump.getFirstChild(); nd != null; nd = nd.getNextSibling()) {
        if (nd.getNodeValue() != null) {
            System.out.println(nd.getNodeValue());
        }
    }
String getNodeName();
    Node ndDoc = (Node)doc.getDocumentElement();
    System.out.println("Document root element type: " + ndDoc.getNodeName());
unsigned short getNodeType();
    public boolean isElement(Node nd) {
        return nd.getNodeType() == Node.ELEMENT_NODE;
    }
String getNodeValue() throws DOMException;

public void setNodeValue(String nodeValue) throws DOMException;
    if (nd.getNodeType() == Node.TEXT_NODE) {
        // make it lowercase
        nd.setNodeValue(nd.getNodeValue().toLowerCase());
    }
Document getOwnerDocument();
    Document doc = elem.getOwnerDocument();
    Text txtAdd = doc.createTextNode("My $.02");
    elem.appendChild(txtAdd);
Node getParentNode();
elem.getParentNode().removeChild(elem);
public String getPrefix();

public void setPrefix(String prefix)
    throws DOMException;

previousSibling

Node getPreviousSibling();
    for (Node nd = ndDump.getLastChild(); nd != null; nd = nd.getPreviousSibling()) {
        if (nd.getNodeValue() != null) {
            System.out.println(nd.getNodeValue());
        }
    }

appendChild (newchild)

public Node appendChild(Node newChild) throws DOMException;
    if (elem.getFirstChild() != null) {
        elem.appendChild(elem.removeChild(elem.getFirstChild()));
    }
public Node cloneNode(boolean deep);
    elem.cloneNode(true);
public boolean hasAttributes();

hasChildNodes ( )

public boolean hasChildNodes();

insertBefore (newchild, refchild)

public Node insertBefore(Node newChild, Node refChild) throws DOMException;
    ndParent.insertBefore(ndNew, ndParent.getFirstChild());
public boolean supports(String feature, String version);

normalize ( ) (

public void normalize();

removeChild (oldchild)

    // from the document tree
    elem.getParentNode().removeChild(elem);
public Node removeChild(Node oldChild) throws DOMException;

replaceChild (newchild, oldchild)

public Node replaceChild(Node newChild, Node oldChild) throws DOMException;
    ndOld.getParentNode().replaceChild(ndNew, ndOld);
    NodeList nlChildren = elem.getChildNodes();
    Node ndChild;

    for (int iNode = 0; iNode < nlChildren.getLength(); iNode++) {
        ndChild = nlChildren.item(iNode);

        if (ndChild.getNodeType() == Node.TEXT_NODE) {
            System.out.println(ndChild.getNodeValue());
        }
    }
unsigned long getLength();

item (index)

public Node item(unsigned long index);

ProcessingInstruction

    ProcessingInstruction pi = doc.createProcessingInstruction("my_app",
            "action=\"save\"");

data

String getData();

public void setData(String data) throws DOMException;
if (pi.getTarget() == "MY_APPLICATION") {
        // check the data attribute for my own application-specific information
        if (pi.getData() == "CHECK_SIBLINGS") {
            // check the siblings
            ...
        }

        pi.setData("SIBLINGS_CHECKED");
    }
String getTarget();
if (pi.getTarget() == "MY_APPLICATION") {
        // do my application-specific processing here
    }

    CharacterData XML example.
    
                This is some character data.
            


    Resulting DOM object tree.
    
        
        
    

splitText (offset)

public Text splitText(unsigned long offset) throws DOMException;
    Text ndText = doc.createTextNode("This text is split.");

    // and split it
    Text ndSplit = ndText.splitText(9);

Copyright 2001 W. Scott Means
smeans@industrialwebmachines.com
Last Modified January 29, 2001