Dom by Kamalakar Dandu

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 30

The Document Object Model (DOM) APIs

Why DOM
ensures proper grammar and wellformedness. The DOM abstracts content away from grammer. simplifies internal document manipulation. Mirrors typical hierarchical and relational database structures

A Simple XML Structure



<customer> <invoice> <linr-item/> </invoice> <address/> <correspondence> <correspondent/> <correspondence-text/> </correspondence> </customer>

The DOM Structure


line-item | | invoice | | correspondent | | address-------customer-----correspondence | | correspondence-text

The DOM specification


DOM specification is maintained by the W3C. DOM Level 1 contains two main sections 1. DOM core level 1. (Interfaces that can assess any structured document) 2. HTML specific extensions to the DOM.

DOM Level 2
Specification currently has the status of candidate Recommendation this means that it has received significant review from its immediate technical community, and now requires implementation and technical feedback from parties external to the W3C.

DOM Level 2 (contd)


support for namespaces Style sheets - includs boject model for style sheets & methods to Query and manipulate the style-sheet. Filters - DOM level 2 adds methods for filtering the Documents. Event model - event model for XML is planned for level 2 DOM Ranges - the level 2 DOM includes functions for manipulation large blocks of text.

Java API for DOM


DocumentBuilderFactory : Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents. (not Thread safe) DocumentBuilder : Defines the API to obtain DOM Document instances from an XML document.

Important Methods In DocumentBuilderFactory


Public DocumentBuilder newDocumentBuilder() Public static DocumentBuilderFactory newInstance() Public void is/setExpandEntityReferences (boolean) Public void is/setIgnoringComments(boolean) Public void is/setIgnoringElementContentWhitespace(boolean) Public void is/setNamespaceAware(boolean) Public void is/setValidating(boolean)

Important Methods In DocumentBuilder


Public boolean isNamespaceAware() Public boolean isValidating() Public Document newDocument() Public Document parse(File f) Public Document parse(InputSource f) Public Document parse(InputStream f) Public void setEntityResolver(EntityResolver er) Public void setErrorHandler(ErrorHandler eh)

Important Interfaces In org.w3c.dom Package


Attr CharacterData Comment Document DocumentFragment DocumentType Element EntityEntityReference Notation ProcessingInstruction Text

Important Methods In Node Interface


Node appendChild(Node newChild) Node cloneNode(boolean deep) NamedNodeMap getAttributes() NodeList getChildNodes() Node getFirstChild() Node getLastChild() String getNamespaceURI() Node getNextSibling()

Important Methods In Node Interface (contd)


String getNodeName() short getNodeType() String getNodeValue() Document getOwnerDocument() Node getParentNode() String getPrefix() Node getPreviousSibling() boolean hasAttributes() boolean hasChildNodes()

Important Methods In Node Interface (contd)


boolean hasChildNodes() Node insertBefore(Node newChild, Node refChild) void normalize() Node removeChild(Node oldChild) Node replaceChild(Node newChild, Node oldChild) void setNodeValue(String nodeValue) void setPrefix(String prefix)

Create the Skeleton


Start with a normal basic logic: public class DomEcho { public static void main(String argv[]) { if (argv.length != 1) { System.err.println("Usage: java DomEcho filename"); System.exit(1); } }// main }// DomEcho

Create the Skeleton (Contd..)


Import the Required Classes: import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.File; import java.io.IOException; import org.w3c.dom.Document; import org.w3c.dom.DOMException;

Create the Skeleton (Contd..)


Declare the DOM public class DomEcho { static Document document; public static void main (String[] args) { .

Create the Skeleton (Contd..)


try { } catch (SAXParseException spe) { // Error generated by the parser System.out.println("\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.out.println(" " + spe.getMessage() ); // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace();

Instantiate the Factory


public static void main(String argv[]) { if (argv.length != 1) { ... } DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); try {

Get a Parser and Parse the File


try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse( new File(argv[0]) ); } catch (SAXParseException spe) {

Create the Skeleton Example


Example : XML : slideSample01.xml Java : DomEcho01.java

Creating an XML DOM Document


Create a Document Object : DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(false); documentBuilderFactory.setNamespaceAware(false); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); Document document = builder.newDocument();

Creating an XML DOM Document (contd)


A method to create an Element :

private Element createElement(Document doc,Node parent,String name, String value) { Element elem=doc.createElement(name);

if(value!=null){ Text text=doc.createTextNode(value); elem.appendChild(text); }


parent.appendChild(elem); return elem; }

Creating an XML DOM Document (contd)


A method to create an Element :

private Attr createAttribute(Document doc, Element element, String attrName, String attrValue) { Attr attr = null; if(attrName != null) attr = doc.createAttribute(attrName);
if(attrValue!=null) attr.setValue(attrValue); if(element != null && attr!=null) element.setAttributeNode(attr); return attr; Example : CreateEmpXML.java

Exercise
Product.xml stores below information

Product Name Price


Monitor keyBoard CPU 10000 1000 12000

Quantity
5 3 6

Write the below programs : 1. Add a new product to the list 2. Update the product price and quantity Reference : DOMReaderDemo.java, ProductDemo.java Note : The Changes made to the Product XML need not be recorded. You are only required to store the changes in DOM tree and display the same.

Validating with XML Schema


Overview of the Validation Process To be notified of validation errors in an XML document,

The factory must configured, and the appropriate error handler set. The document must be associated with at least one schema, and possibly more.

Configuring the DocumentBuilder Factory


static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schema Language"; static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); } catch (IllegalArgumentException x) { // Happens if the parser does not support JAXP 1.2 }

Associating a Document with a Schema


There are two ways to do that: 1. With a schema declaration in the XML document. 2. By specifying the schema(s) to use in the application.

To specify the schema definition in the document, you would create XML like this:
<documentRoot xmlns:xsi=http://www.w3.org/2001/XMLSchemainstance
xsi:noNamespaceSchemaLocation=YourSchem aDefinition.xsd > ...

Specifying the schema file in the application


static final String schemaSource = "YourSchemaDefinition.xsd"; static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; ... DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ... factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(schemaSource)); Example : Java File : ValidateSchema.java XML : Greeting.xml

XSD : Greeting.xsd

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy