+ All Categories
Home > Documents > 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

Date post: 19-Jan-2016
Category:
Upload: ethel-ward
View: 214 times
Download: 0 times
Share this document with a friend
105
1 Processing XML with Processing XML with Java Java DBI – Representation and Management of Data on the Internet
Transcript
Page 1: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

1

Processing XML with JavaProcessing XML with Java

DBI – Representation and Management of Data on the Internet

Page 2: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

2

XMLXML

• XML is eXtensible Markup Language• It is a metalanguage:

– A language used to describe other languages using “markup” tags that describe properties of the data

• Designed to be structured– Strict rules about how data can be formatted

• Designed to be extensible– Can define own terms and markup

Page 3: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

3

XML FamilyXML Family

• XML is an official recommendation of the W3C

• Aims to accomplish what HTML cannot and be simpler to use and implement than SGML

HTML XMLSGML

XHTML

Page 4: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

4

The Essence of XMLThe Essence of XML

• Syntax– The permitted arrangement or structure of letters and

words in a language as defined by a grammar (XML)

• Semantics– The meaning of letters or words in a language

• XML uses Syntax to add Semantics to the documents

Page 5: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

5

Using XMLUsing XML

• In XML there is a separation of the content from the display

• XML can be used for:– Data representation– Data exchenge

Page 6: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

6

Databases and XMLDatabases and XML

• Database content can be presented in XML– XML processor can

access DBMS or file system and convert data to XML

– Web server can serve content as either XML or HTML

Page 7: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

7

HTML vs. XMLHTML vs. XML<OL>

<LI>HTML allows <B><I>improper nesting</B></I>. <LI>HTML allows start tags, without end tags, like the <BR> tag. <LI>HTML allows <FONT COLOR=#9900CC>attribute values</FONT> without quotes <li>HTML is case-insensitive <LI>White space is not important in HTML </OL>

<OL> <LI>XML requires <B><I>proper nesting</I></B>.</LI> <LI>XML requires empty tags to be identified with a trailing slash, as in <BR/>.</LI> <LI>XML requires <FONT COLOR="#9900CC">quoted attribute values</FONT>.</LI> <LI>XML is case-sensitive <LI>White space is important in XML </OL>

Page 8: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

8

Some Basic Rules for XMLSome Basic Rules for XML

• All tags must be balanced - <TAG>...</TAG>• Empty tags expressed - <EMPTY_TAG/>• Tags must be nested - <B><I>…</I></B>• All element attributes must be quoted -

<TAG name=“value”>• Text is case-sensitive - <TAG> != <Tag>• Comments are allowed - <!-- … -->• Must begin - <?xml version=‘1.0’ ?>• Special characters must be escaped (e.g., &gt; for >)

Page 9: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

9

SAX ParserSAX Parser

• Set of interfaces implemented by an application

• The application – reads in an XML file – generates events when it encounters items in

the XML file

Page 10: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

10

SAX Parser EventsSAX Parser Events

• A SAX parser generates events– at the start and end of a document, – at the start and end of an element, – when it finds characters inside an element, and

at several other points

• User writes the Java code that handles each event, and decides what to do with the information from the parser

Page 11: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

11

Page 12: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

12

When to (not) use SAXWhen to (not) use SAX

• Ideal for simple operations on XML files– E.g. reading and extracting elements

• Good for very large XML files (c.f. DOM)

• Not good if we want to manipulate XML structure

• Not designed for writing out XML

Page 13: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

13

DOMDOM

• Document Object Model

• Set of interfaces for an application that reads an XML file into memory and stores it as a tree structure

• The abstract API allows for constructing, accessing and manipulating the structure and content of XML and HTML documents

Page 14: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

14

What a DOM Parser GivesWhat a DOM Parser Gives

• When you parse an XML document with a DOM parser, you get back a tree structure that contains all of the elements of your document

• The DOM provides a variety of functions you can use to examine the contents and structure of the document

Page 15: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

15

Page 16: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

16

Why to Use DOMWhy to Use DOM

• Task of writing parsers is reduced to coding against an API for the document structure

• Domain-specific frameworks will be written on top of DOM

Page 17: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

17

Page 18: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

18

Page 19: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

19

DOM vs. SAXDOM vs. SAX

• If your document is very large and you only need a few elements - use SAX

• If you need to process many elements and perform manipulations on XML - use DOM

• If you need to access the XML many times - use DOM

Page 20: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

20

What Would You Choose forWhat Would You Choose for

• Processing an XML document in a server?

• Processing an XML document in a remote client?

• Direct access to element in the XML file (e.g., index based on paths)

• A visual tool for traversal over the document tree?

Page 21: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

21

XML ParsersXML Parsers

Page 22: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

22

XML ParsersXML Parsers

• There are several different ways to categorise parsers:– Validating versus non-validating parsers – Parsers that support the Document Object

Model (DOM) – Parsers that support the Simple API for XML

(SAX) – Parsers written in a particular language (Java,

C++, Perl, etc.)

Page 23: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

23

Non-Validating ParsersNon-Validating Parsers

• Speed and efficiency– It takes a significant amount of effort for an

XML parser to process a DTD and make sure that every element in an XML document follows the rules of the DTD.

• If we only want to find tags and extract information – we should use a non-validating parser

Page 24: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

24

Using an XML ParserUsing an XML Parser

• Three basic steps in using an XML parser– Creating a parser object – Passing the XML document to the parser – Processing the results

• Generally, writing out XML is not in the scope of parsers (though some may implement proprietary mechanisms)

Page 25: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

25

SAX – Simple API for XMLSAX – Simple API for XML

Page 26: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

26

The SAX ParserThe SAX Parser

• SAX parser is an event-driven API– An XML document is sent to the SAX parser– The XML file is read sequentially– The parser notifies the class when events

happen, including errors– The events are handled by the implemented

API methods to handle events that the programmer implemented

Page 27: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

27

SAX ParserSAX Parser• A SAX parser generates events

– At the start and end of a document– At the start and end of an element – When it finds characters inside an element– Upon encountering errors– Upon encountering negligible whitespace– and at several other points

• It uses a callback mechanism to notify the application

• Java code that handles each event implements the events handling

Page 28: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

28

The The org.xml.sax.*org.xml.sax.* Package Package

• SAX Interfaces and Classes– Parser– DocumentHandler– DTDHandler– ErrorHandler– EntityResolver– AttributeList– Locator

Page 29: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

29

The Apache XML Parser (xerces)The Apache XML Parser (xerces)

import org.xml.sax.*;

import org.apache.parsers.*;

class MyClass {

SAXParser myParser;

try {

myParser.parse("file:/myFile.xml");

} catch (SAXException err) {…}

}

Page 30: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

30

The Parser InterfaceThe Parser Interface

• Registers other objects for callbacks– void setDocumentHandler(DocumentHandler handler)– void setDTDHandler(DTDHandler handler)– void setErrorHandler(ErrorHandler handler)– void setEntityResolver(EntityResolver resolver)

• Starts parsing with parse() method call• When the parser hits a significant item, it stops

reading and calls a registered object• The parser continues reading the XML file once

the called method has returned

Page 31: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

31

The DocumentHandler InterfaceThe DocumentHandler Interface• This interface is used to receive basic markup

events from the parser• It is usually implemented by a class that activates

the parser

class myClass implements DocumentHandler {

myParser.setDocumentHandler(this);

}

Page 32: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

32

DocumentHandler MethodsDocumentHandler Methods

• void startDocument()• void endDocument()• void startElement(String name,

AttributeList attrs)• void endElement(String name)• void characters(char[] ch,

int start, int length)

• void ignorableWhitespace(char[] ch, int start, int length)

• void processingInstruction(String target, String data)

Page 33: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

33

Bachelor TagsBachelor Tags

• What happen when the parser parses a bachelor tag?

<dbi id=‘1’/>

Page 34: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

34

AttributeList InterfaceAttributeList Interface

• Elements may have attributes– We have a wrapper object for all attribute

details that implements the AttributeList interface

– It cannot distinguish attributes that are defined explicitly from those that are specified in the DTD

Page 35: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

35

AttributeList Interface (cont.)AttributeList Interface (cont.)

int getLength();

String getName(int i);

String getType(int i);

String getValue(int i);

String getType(String name);

String getValue(String name);

Page 36: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

36

Attributes TypesAttributes Types

• The following are possible types for attributes:

– "CDATA",

– "ID",

– "IDREF", "IDREFS",

– "NMTOKEN", "NMTOKENS",

– "ENTITY", "ENTITIES",

– "NOTATION"

Page 37: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

37

AttributeListImplAttributeListImpl

• The class is in the package org.xml.sax.helpers.*

• Include methods such as:– addAtrribute, removeAttribute– clear– getName, getType, getValue– getLength

By name or by index

Page 38: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

38

ErrorHandler InterfaceErrorHandler Interface• If we want to know about warnings and

errors– We implement the ErrorHandler interface

and register it with the parser class– The handler does not report where the error

occurred

• We have three levels of exception:void error(SAXParseException ex);

void fatalError(SAXParserExcpetion ex);

void warning(SAXParserException ex);

Page 39: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

39

Locator InterfaceLocator Interface

• Associates a SAX event with a document location– The parser can inform

• the application of the entity, • line number and character number of a warning or

error,

– if it is a class implementing the Locator interface and it is registered with the DocumentHandler

Page 40: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

40

Locator MethodsLocator Methods

int getLineNumber();

int getColumnNumber();

String getSystemId();

(i.e., return the URL)

String getPublicId();

Page 41: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

41

DTDHandler InterfaceDTDHandler Interface

• Provides callback methods to receive notification of DTD events

• It is a mechanism to inform an application about any binary entity that the parser encounters

Page 42: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

42

DTD HandlerDTD Handler

notationDecl(String name,

String publicId,

String systemId);

unparsedEntityDecl(String name,

String publicId,

String systemId,

String notationName);

Page 43: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

43

InputSource ClassInputSource Class

• Possible to specify a byte or character stream for the input to the parser

• The InputSource class contains methods that specify the exact nature of the data source

Page 44: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

44

EntityResolver InterfaceEntityResolver Interface

• The application is not aware of the physical structure of the XML data

• The parser contains an entity manager that hides the complexity from the application which sees the data as a single stream

• Can intercept references to entities by implementing the EntityResolver interface

Page 45: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

45

EntityResolver Interface (2)EntityResolver Interface (2)

• When the parser encounters an entity, it passes the system and/or public identifier to the application– Return value is ‘null’ or new InputSource

Page 46: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

46

EntityResolver Interface (2)EntityResolver Interface (2)

public InputSource resolveEntity(String publicID,

String systemID) {

if (systemID.equals("Disclaimer") || publicID.equals

("-//EBI//TEXT Disclaimer//EN")) return (new

InputSource(file:/xml/disc.xml));

}

}

Page 47: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

47

HandlerBase ClassHandlerBase Class

• This class implements SAX interfaces in a sensible, default way

DocumentHandler, DTDHandler, EntityResolver and ErrorHandler

• Can be used for partial implementation of the interfaces

• This class can be extended:import org.xml.sax.HandlerBase;

public class myHandler extends HandlerBase() { …}

Page 48: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

48

ParserFactory ClassParserFactory Class

• A helper class– Provides convenient methods for dynamically

loading SAX parsers

makeParser() (Uses org.xml.sax.parser system property)

makeParser(String className)

Page 49: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

49

ExampleExample

• An example of indenting an XML document (as part of a server)

XMLIndent.java

Page 50: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

50

Page 51: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

51

Page 52: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

52

Page 53: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

53

DOM – Document Object ModelDOM – Document Object Model

Page 54: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

54

DOM StandardsDOM Standards

• DOM 1.0 standard from www.w3.org• Assumes an object-oriented approach• Composed of number of interfaces

– org.w3c.dom.*

• Central class is 'Document' (DOM tree)• Standard does not include

– Tree walking– Writing out XML format

Page 55: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

55

Creating a DOM TreeCreating a DOM Tree

• A DOM implementation has a method to pass an XML file to a factory object

• The factory object returns a Document object that represents the root element of a whole document

• On the Document objects, DOM standard interface can be used to interact with XML structure

Page 56: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

56

Line Of WorkLine Of Work

DOM Parser DOM TreeXML File

API

Application

Page 57: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

57

DOM TreeDOM Tree

Document

Document Type Element

Attribute Element ElementAttribute Text

ElementText Entity Reference TextText

TextComment

Page 58: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

58

Normalizing a TreeNormalizing a Tree

• Normalizing a DOM Tree has two effects:– Combine adjacent textual nodes– Eliminate empty textual nodes– We can apply a normalize() method to the

document element

Page 59: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

59

DOMParserDOMParser

• DOMParser extends XMLParser– Important Methods:

• void parse(InputSource source)           Parses the specified input source

• void parse(java.lang.String systemId)           Parses the input source specified by the given

system identifier

•  Document getDocument()           Returns the document

Page 60: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

60

DOMParser

parse(xml-file) getDocument()

Document

getChildNodes()

NodeList …

Page 61: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

61

Creating a DOM Tree (2)Creating a DOM Tree (2)import java.io.*; import org.w3c.dom.*;import org.apache.xerces.dom.*;import org.apache.xerces.parsers.*;

public class myClass {

DOMParser parser = new DOMParser();

try {

parser.parse(“file:/doc.xml”);

} ccatch (IOException err) {…} catch (SAXException err) {…}

catch (DOMException err) {…}

Document document = parser.getDocument();…

Page 62: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

62

DOM Interfaces and ClassesDOM Interfaces and ClassesDocumentFragment

Document

CharacterDataText

Comment

CDATASection

Attr

Element

DocumentType

Notation

Entity

EntityReference

ProcessingInstruction

NodeNodeList

NamedNodeMap

DocumentType

Figure as from “The XML Companion” - Neil Bradley

Page 63: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

63

DOM InterfacesDOM Interfaces

• The DOM defines several Java interfaces– NodeThe base data type of the DOM – Element Represents element– AttrRepresents an attribute of an element– TextThe content of an element or attribute– Document Represents the entire XML

document. A Document object is often referred to as a DOM tree

Page 64: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

64

Node InterfaceNode Interface

• Basic object of DOM (single node in tree)• Nodes describe

• Node collections– NodeList, NamedNodeMap, DocumentFragment

• Several nodes extend the Node interface

ElementsAttributesTextCommentsCDATA sections

Entity declarationsEntity referencesNotation declarationsEntire documentsProcessing instructions

Page 65: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

65

Node MethodsNode Methods

• Three categories of methods– Node characteristics

• name, type, value

– Contextual location and access to relatives• parents, siblings, children, ancestors, descendants

– Node modification• Edit, delete, re-arrange child nodes

Page 66: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

66

Node Methods (2)Node Methods (2)short getNodeType();

String getNodeName();

String getNodeValue() throws DOMException;

void setNodeValue(String value) throws DOMException;

boolean hasChildNodes();

NamedNodeMap getAttributes();

Document getOwnerDocument();

Page 67: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

67

Node Types - getNodeType()Node Types - getNodeType()

ELEMENT_NODE = 1

ATTRIBUTE_NODE = 2

TEXT_NODE = 3

CDATA_SECTION_NODE = 4

ENTITY_REFERENCE_NODE = 5

ENTITY_NODE = 6

PROCESSING_INSTRUCTION_NODE = 7

COMMENT_NODE = 8

DOCUMENT_NODE = 9

DOCUMENT_TYPE_NODE = 10

DOCUMENT_FRAGMENT_NODE = 11

NOTATION_NODE = 12

if (myNode.getNodeType() == Node.ELEMENT_NODE) { //process node …}

Page 68: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

68

Node Names and ValuesNode Names and Values

• Every node has a name and possibly a value

• Name is not a unique identifier (only location)Type Interface Name Name Value

ATTRIBUTE_NODE Attr Attribute name Attribute value

DOCUMENT_NODE Document #document NULL

DOCUMENT_FRAGMENT_NODE DocumentFragment #document-fragment NULL

DOCUMENT_TYPE_NODE DocumentType DOCTYPE name NULL

CDATA_SECTION_NODE CDATASection #cdata-section CDATA content

COMMENT_NODE Comment Entity name Content string

ELEMENT_NODE Element Tag name NULL

ENTITY_NODE Entity Entity name NULL

ENTITY_REFERENCE_NODE EntityReference Entity name NULL

NOTATION_NODE Notation Notation name NULL

PROCESSING_INSTRUCTION_NODE

ProcessingInstruction Target string Content string

TEXT_NODE Text #text Text string

Table as from “The XML Companion” - Neil Bradley

Page 69: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

69

Type Interface Name Name Value

ATTRIBUTE_NODE Attr Attribute name Attribute value

DOCUMENT_NODE Document #document NULL

DOCUMENT_FRAGMENT_NODE DocumentFragment #document-fragment NULL

DOCUMENT_TYPE_NODE DocumentType DOCTYPE name NULL

CDATA_SECTION_NODE CDATASection #cdata-section CDATA content

COMMENT_NODE Comment Entity name Content string

ELEMENT_NODE Element Tag name NULL

ENTITY_NODE Entity Entity name NULL

ENTITY_REFERENCE_NODE EntityReference Entity name NULL

NOTATION_NODE Notation Notation name NULL

PROCESSING_INSTRUCTION_NODE

ProcessingInstruction Target string Content string

TEXT_NODE Text #text Text string

Page 70: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

70

Child NodesChild Nodes

• Most Nodes cannot have children, except– Document, DocumentFragment, Element

• Can check for presence of children– if (myNode.hasChildNodes()) { //process children of myNode … }

Page 71: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

71

Node NavigationNode Navigation

• Every node has a specific location in tree• Node interface specifies methods to find

surrounding nodes– Node getFirstChild();– Node getLastChild();– Node getNextSibling();– Node getPreviousSibling();– Node getParentNode();– NodeList getChildNodes();

Page 72: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

72

Node Navigation (2)Node Navigation (2)

getFirstChild()

getPreviousSibling()

getChildNodes()

getNextSibling()

getLastChild()

getParentNode()

Node parent = myNode.getParentNode();if (myNode.hasChildren()) { NodeList children = myNode.getChildNodes();}

Figure as from “The XML Companion” - Neil Bradley

Page 73: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

73

Node ManipulationNode Manipulation

• Children of a node in a DOM tree can be manipulated - added, edited, deleted, moved, copied, etc.

Node removeChild(Node old) throws DOMException;

Node insertBefore(Node new, Node ref) throws DOMException;

Node appendChild(Node new) throws DOMException;

Node replaceChild(Node new, Node old) throws DOMException;

Node cloneNode(boolean deep);

Page 74: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

74

Node Manipulation (2)Node Manipulation (2)

Ref

New

insertBefore

Old

New

replaceChild

cloneNode

Shallow 'false'

Deep 'true'

Figure as from “The XML Companion” - Neil Bradley

Page 75: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

75

Document::Node InterfaceDocument::Node Interface

• Represents entire XML document (tree root)

• Methods//Information from DOCTYPE - See 'DocumentType'DocumentType getDocumentType();

//Information about capabilities of DOM implementationDOMImplementation getImplementation();

//Returns reference to root node elementElement getDocumentElement();

//Searches for all occurrences of 'tagName' in nodesNodeList getElementsByName(String tagName);

Page 76: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

76

Document::Node Interface (2)Document::Node Interface (2)

• Factory methods for node creationElement createElement(String tagName) throws DOMException;

DocumentFragment createDocumentFragment();

Text createTextNode(String data);

Comment createComment(String data);

CDATASection createCDATASection(String data) throws DOMException;

ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException;

Attr createAttribute(String name) throws DOMException;

EntityReference createEntityReference(String name) throws DOMException;

Page 77: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

77

DocumentType::Node InterfaceDocumentType::Node Interface

• Information about document encapsulated in DTD representation

• DOM 1.0 doesn’t allow editing of this node//Returns name of documentString getName();

//Returns general entities declared in DTDNamedNodeList getEntities();

//Returns notations declared in DTDNamedNodeList getNotations();

Page 78: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

78

Element::Node InterfaceElement::Node Interface

• Two categories of methods– General element methods

– Attribute management methods

String getTagName();NodeList getElementsByTagName();void normalize();

String getAttribute(String name);void setAttribute(String name, String value)

throws DOMException;void removeAttribute(String name)

throws DOMException;Attr getAttributeNode(String name);void setAttributeNode(Attr new)

throws DOMException;void removeAttributeNode(Attr old)

throws DOMException;

Page 79: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

79

Element::Node Interface (2)Element::Node Interface (2)

• Only Element objects have attributes but attribute methods of Element are simple– Need name of attribute

– Cannot distinguish between default value specified in DTD and given in XML file

– Cannot determine attribute type [String]

• Instead use getAttributes() method of Node– Returns Attr objects in a NamedNodeMap

Page 80: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

80

Attr::Node InterfaceAttr::Node Interface

• Interface to objects holding attribute data

• Entity ref's are children of attribute's

//Get name of attributeString getName();

//Get value of attributeString getValue();

//Change value of attributevoid setValue(String value);

//if 'true' - attribute defined in element, else in DTDboolean getSpecified();

Page 81: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

81

Attr::Node Interface (2)Attr::Node Interface (2)

• Attributes not considered part of DOM – parentNode, previousSibling and nextSibling have null value for Attr object

• Create attribute objects using factory method of Document//Create the empty Attribute nodeAttr newAttr = myDoc.createAttribute("status");

//Set the value of the attributenewAttr.setValue("secret");

//Attach the attribute to an elementmyElement.setAttributeNode(newAttr);

Page 82: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

82

CharacterData::Node InterfaceCharacterData::Node Interface

• Useful general methods for dealing with text

• Not used directly– sub-classed to Text and Comment Node types

String getData() throws DOMException;void setData(String data) throws DOMException;int getLength();void appendData(String data) throws DOMException;String substringData(int offset, int length)

throws DOMException;void insertData(int offset, String data)

throws DOMException;void deleteData(int offser, int length)

throws DOMException;void replaceData(int offset, int length, String data)

throws DOMException;

Page 83: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

83

Text::Node InterfaceText::Node Interface

• Represents textual content of Element or Attr– Usually children of these nodes

• Always leaf nodes• Single method added to CharacterData

– Text splitText(int offset) throws DOMException

• Factory method in Document for creation• Calling normalize() on an Element merges

its Text objects

Page 84: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

84

CDATASection::Text InterfaceCDATASection::Text Interface

• Represents CDATA that is not to be interpreted as markup (the only delimiter recognised is the "]]>" string that ends the CDATA section)

• The DOMString attribute of the Text node holds the text of the CDATA section

• No methods added to CharacterData• Factory method in Document for creation

– CDATASection newCDATA = myDoc.createDATASection("press <<<ENTER>>>");

Page 85: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

85

Comment::Text InterfaceComment::Text Interface

• Represents comments

• all the characters between starting '<!--' and ending '-->'

• No methods added to CharacterData• Factory method in Document for creation

– Comment newComment = myDoc.createComment(" my comment "); //Note

spaces

Page 86: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

86

ProcessingInstruction::Node ProcessingInstruction::Node InterfaceInterface

• Represent processing instruction declarations– Name of node is target application name– Value of node is target application command

• Factory method in Document for creation– ProcessingInstruction newPI =

myDoc.createProcessingInstruction(“myProgs/ghostview”, “page.ps”);

//Get the content of the processing instructionString getData() //Set the content of the processing instructionvoid setData(String data) //The target of this processing instructionString getTarget();

Page 87: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

87

EntityReference::Node InterfaceEntityReference::Node Interface

• DOM includes interfaces for handling notations, entities and entity references– If the entities have not been replaced by the

parser

Element Text

Text

EntityReference Text

An

value

xmleXtensible

MarkupLanguage

<!ENTITY xml "eXtensible Markup Language"><para>An &xml; value</para>

valuename

Figure as from “The XML Companion” - Neil Bradley

Page 88: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

88

Entity::Node InterfaceEntity::Node Interface

• Represents an entity, either parsed or unparsed, in an XML document– Parser may replace entity references, or create EntityReference nodes

• Must retain Entity for non-parsable data• Extends Node interface and adds methods

• For non-parsable entities - can get notation nameString getPublicId();String getSystemId();String getNotationName();

Page 89: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

89

Entity::Node Interface (2)Entity::Node Interface (2)

• A parsable Entity may have children that represent the replacement value of the entity

• All entities of a Document accessed with getEntities() method in DocumentType

<!ENTITY MyBoat PUBLIC "BOAT" SYSTEM "boat.gif" NDATA GIF>

String publicId = ent.getPublicId(); //BOAT

String systemId = ent.getSystemId(); //boat.gif

String notation = ent.getNotationName(); //GIF

Figure as from “The XML Companion” - Neil Bradley

Page 90: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

90

Notation::Node InterfaceNotation::Node Interface

• Each notation declaration in DTD represented by a Notation node

• Methods added to Node interface

• All notations of a Document accessed with getNotations() method in DocumentType object

//Returns content of PUBLIC identifierString getPublicId();

//Returns content of SYSTEM identifierString getSystemId();

Page 91: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

91

NodeList InterfaceNodeList Interface

• Holds collection of ordered Node objects

• Two methods//Find number of Nodes in NodeListint getLength();

//Return the i-th NodeNode item(int index);-------------------------------------------------Node child;NodeList children = element.getChildNodes()'for (int i = 0; i < children.getLength(); i++) { child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { System.out.println(child.getNodeName()); }}

Page 92: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

92

NamedNodeMap InterfaceNamedNodeMap Interface

• Holds collection of unordered Node objects– E.g. Attribute, Entity and Notation

• Unique names are essential as nodes are accessed by nameNamedNodeMap myAttributes = myElement.getAttributes();NamedNodeMap myEntities = myDocument.getEntities();NamedNodeMap myNotations = myDocument.getNotations();------------------------------------------------------int getLength();Node item(int index);Node getNamedItem(String name);Node setNamedItem(Node node) throws DOMException;//Node!Node removeNamedItem(String name) throws DOMException;

Page 93: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

93

DocumentFragment::Node DocumentFragment::Node InterfaceInterface

• Fragment of Document can be temporarily stored in DocumentFragment node– Lightweight object, e.g. for 'cut-n-paste'

• When attached to another Node - destroys itself (very useful for adding siblings to tree)

DocumentFragment

DOM tree

New DOM tree

Figure as from “The XML Companion” - Neil Bradley

Page 94: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

94

DOMImplementation InterfaceDOMImplementation Interface

• Interface to determine level of support in DOM parser– hasFeature(String feature, String version);

– if (theParser.hasFeature("XML", "1.0") { //XML is supported …}

Page 95: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

95

DOM ObjectsDOM Objects

• DOM object compiled XML

• Can save time and effort if send and receive DOM objects instead of XML source– Saves having to parse XML files into DOM at

sender and receiver– But, DOM object may be larger than XML

source

Page 96: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

96

ExamplesExamples

• DOMTest

• DTD

• XML

• Counting Result

Page 97: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

97

Page 98: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

98

Java + XML = JDOMJava + XML = JDOM

Page 99: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

99

What is JDOM?What is JDOM?• JDOM is a way to represent an XML document for

easy and efficient reading, manipulation, and writing– Straightforward API– Lightweight and fast– Java-optimized

• Despite the name similarity, it's not build on DOM or modeled after DOM– Although it integrates well with DOM and SAX

• An open source project with an Apache-style license

Page 100: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

100

The JDOM PhilosophyThe JDOM Philosophy• JDOM should be straightforward for Java programmers

– Use the power of the language (Java 2)– Take advantage of method overloading, the Collections

APIs, reflection, weak references– Provide conveniences like type conversions

• JDOM should hide the complexities of XML wherever possible– An Element has content, not a child Text node with content– Exceptions should contain useful error messages– Give line numbers and specifics, use no SAX or DOM

specifics

Page 101: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

101

More JDOM PhilosophyMore JDOM Philosophy

• JDOM should integrate with DOM and SAX– Support reading and writing DOM documents

and SAX events– Support runtime plug-in of any DOM or SAX

parser– Easy conversion from DOM/SAX to JDOM– Easy conversion from JDOM to DOM/SAX

Page 102: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

102

The Historical Alternatives: The Historical Alternatives: DOMDOM

• DOM is a large API designed for complex environments– A W3C standard, developed by W3C working groups– Implemented by products like Xerces– Represents a document tree fully held in memory– Has to have the same API on multiple languages– Reading and changing the document is non-intuitive– Fairly heavyweight to load and store in memory– http://www.w3.org/DOM

Page 103: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

103

The Historical Alternatives: SAXThe Historical Alternatives: SAX

• SAX is a lightweight API designed for fast reading– Public domain API from David Megginson and XML-

DEV mailing list– Implemented by products like Xerces– Callback mechanism reports when document elements are

encountered– Lightweight since the document is never entirely in

memory– Does not support modifying the document– Does not support random access to the document– Fairly steep learning curve to use correctly

Page 104: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

104

Do you need JDOM?Do you need JDOM?

• JDOM is a lightweight API– Its design allows it to hold less in memory

• JDOM can represent a full document– Not all must be in memory at once

• JDOM supports document modification– And document creation from scratch, no

"factory"

Page 105: 1 Processing XML with Java DBI – Representation and Management of Data on the Internet.

105

For More InformationFor More Information

• To get more information on JDOM, see: http://www.jdom/org


Recommended