Docsity

More DOM - Advance Java Web Technology - Lecture Slides, Slides of Computer Science

Partial preview of the text

Download More DOM - Advance Java Web Technology - Lecture Slides and more Slides Computer Science in PDF only on Docsity!

More DOM

Manipulating DOM trees

  • DOM, unlike SAX, gives you the ability to create and modify XML trees
  • There are a few roadblocks along the way
    • Practically everything in the JAXP implementation is an interface, with a few abstract classes
    • Interfaces, such as Node, don’t have constructors; this makes it hard to get started
    • Since DOM was designed to be applicable from a number of languages, many things are not done “the Java way”
  • Once you get past these problems, the individual methods are pretty straightforward - Even with straightforward methods, working with trees is seldom simple

Creating a DOM

import javax.xml.parsers.*; import org.w3c.dom.Document;

try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); } catch (ParserConfigurationException e) { ... }

The rest of the methods

• Most of the other methods are either instance

methods of a Document object, or are

inherited from Node

  • A few are from Attr, Text, Entity, and so on

• Almost all of these methods may throw a

DOMException

• I’ll just go through some of the more

important methods briefly

  • The details can be looked up in the API if needed

Methods inherited from Node

  • public Node appendChild(Node newChild)
  • public Node insertBefore(Node newChild, Node refChild)
  • public Node removeChild(Node oldChild)
  • public Node replaceChild(Node newChild, Node oldChild)
  • setNodeValue(String nodeValue)
    • What this does depends on the type of node
  • public void setPrefix(String prefix)
  • public void normalize()
    • Combines adjacent TextNodes

Methods of Element

  • public void setAttribute(String name, String value)
  • public Attr setAttributeNode(Attr newAttr)
  • public void setAttributeNodeNS(String namespaceURI, String qualifiedName, String value)
  • public Attr setAttributeNodeNS(Attr newAttr)
  • public void removeAttribute(String name)
  • public void removeAttributeNS(String namespaceURI, String localName)
  • public Attr removeAttributeNode(Attr oldAttr)

Writing out the DOM as XML

• There are no Java-supplied methods for

writing out a DOM as XML

• Writing out a DOM is conceptually simple—it’s

just a tree walk

  • However, there are a lot of details—various node

types and so on—so doing a good job isn’t

complicated, but it is lengthy

The End