dom by kamalakar dandu

Upload: kamalakar-dandu

Post on 05-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Dom by Kamalakar Dandu

    1/30

    The Document Object Model (DOM) APIs

  • 8/2/2019 Dom by Kamalakar Dandu

    2/30

    Why DOM

    ensures proper grammar and well-formedness.

    The DOM abstracts content away fromgrammer.

    simplifies internal document manipulation.

    Mirrors typical hierarchical and relationaldatabase structures

  • 8/2/2019 Dom by Kamalakar Dandu

    3/30

    A Simple XML Structure

  • 8/2/2019 Dom by Kamalakar Dandu

    4/30

    The DOM Structure

    line-item

    |

    |

    invoice

    |

    | correspondent

    | |

    address-------customer-----correspondence

    |

    |

    correspondence-text

  • 8/2/2019 Dom by Kamalakar Dandu

    5/30

    The DOM specification

    DOM specification is maintained by theW3C.

    DOM Level 1

    contains two main sections

    1. DOM core level 1.

    (Interfaces that can assess any

    structured document)2. HTML specific extensions to theDOM.

  • 8/2/2019 Dom by Kamalakar Dandu

    6/30

    DOM Level 2

    Specification currently has the status ofcandidate Recommendation this meansthat it has received significant review from

    its immediate technical community, andnow requires implementation and technical

    feedback from parties external to the

    W3C.

  • 8/2/2019 Dom by Kamalakar Dandu

    7/30

    DOM Level 2 (contd)

    support for namespaces

    Style sheets - includs boject model for stylesheets & 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.

  • 8/2/2019 Dom by Kamalakar Dandu

    8/30

    Java API for DOM

    DocumentBuilderFactory : Defines afactory API that enables applications toobtain a parser that produces DOM object

    trees from XML documents. (not Threadsafe)

    DocumentBuilder : Defines the API to

    obtain DOM Document instances from anXML document.

  • 8/2/2019 Dom by Kamalakar Dandu

    9/30

    Important Methods InDocumentBuilderFactory

    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)

  • 8/2/2019 Dom by Kamalakar Dandu

    10/30

    Important Methods InDocumentBuilder

    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)

  • 8/2/2019 Dom by Kamalakar Dandu

    11/30

    Important Interfaces Inorg.w3c.dom Package

    Attr

    CharacterData

    Comment

    Document

    DocumentFragment

    DocumentType

    Element

    EntityEntityReference

    Notation

    ProcessingInstruction

    Text

  • 8/2/2019 Dom by Kamalakar Dandu

    12/30

    Important Methods InNode Interface

    Node appendChild(Node newChild)

    Node cloneNode(boolean deep)

    NamedNodeMap getAttributes()

    NodeList getChildNodes()

    Node getFirstChild()

    Node getLastChild()

    String getNamespaceURI()

    Node getNextSibling()

  • 8/2/2019 Dom by Kamalakar Dandu

    13/30

    Important Methods InNode Interface (contd)

    String getNodeName()

    short getNodeType()

    String getNodeValue()

    Document getOwnerDocument() Node getParentNode()

    String getPrefix()

    Node getPreviousSibling() boolean hasAttributes()

    boolean hasChildNodes()

  • 8/2/2019 Dom by Kamalakar Dandu

    14/30

    Important Methods InNode Interface (contd)

    boolean hasChildNodes()

    Node insertBefore(Node newChild, Node refChild)

    void normalize()

    Node removeChild(Node oldChild)

    Node replaceChild(Node newChild, NodeoldChild)

    void setNodeValue(String nodeValue)

    void setPrefix(String prefix)

  • 8/2/2019 Dom by Kamalakar Dandu

    15/30

    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

  • 8/2/2019 Dom by Kamalakar Dandu

    16/30

    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;

  • 8/2/2019 Dom by Kamalakar Dandu

    17/30

    Create the Skeleton (Contd..)

    Declare the DOM

    public class DomEcho {

    static Document document;

    public static void main (String[] args) {

    .

  • 8/2/2019 Dom by Kamalakar Dandu

    18/30

    try {

    } catch (SAXParseException spe) {// Error generated by the parserSystem.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();

    }

    Create the Skeleton (Contd..)

  • 8/2/2019 Dom by Kamalakar Dandu

    19/30

    Instantiate the Factory

    public static void main(String argv[]) {if (argv.length != 1) {...

    }DocumentBuilderFactory factory

    =DocumentBuilderFactory.newInstance();

    try {

  • 8/2/2019 Dom by Kamalakar Dandu

    20/30

    Get a Parser and Parse the File

    try {

    DocumentBuilder builder = factory.newDocumentBuilder();

    document = builder.parse( new File(argv[0]) );

    } catch (SAXParseException spe) {

  • 8/2/2019 Dom by Kamalakar Dandu

    21/30

    Create the SkeletonExample

    Example :

    XML : slideSample01.xml

    Java : DomEcho01.java

  • 8/2/2019 Dom by Kamalakar Dandu

    22/30

    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();

  • 8/2/2019 Dom by Kamalakar Dandu

    23/30

    Creating an XML DOM Document(contd)

    A method to create an Element :

    private Element createElement(Document doc,Nodeparent,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;

    }

  • 8/2/2019 Dom by Kamalakar Dandu

    24/30

    Creating an XML DOM Document

    (contd)

    A method to create an Element :

    private Attr createAttribute(Document doc, Elementelement, 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

  • 8/2/2019 Dom by Kamalakar Dandu

    25/30

    Exercise

    Product.xml stores below information

    Product Name Price Quantity

    Monitor 10000 5

    keyBoard 1000 3

    CPU 12000 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 berecorded. You are only required to store the changes in DOM treeand display the same.

  • 8/2/2019 Dom by Kamalakar Dandu

    26/30

    Validating with XML Schema

    Overview of the Validation Process

    To be notified of validation errors in anXML document,

    The factory must configured, andthe appropriate error handler set.

    The document must be associated withat least one schema, and possiblymore.

  • 8/2/2019 Dom by Kamalakar Dandu

    27/30

    Configuring the DocumentBuilderFactory

    static final String JAXP_SCHEMA_LANGUAGE= "http://java.sun.com/xml/jaxp/properties/schemaLanguage";

    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}

  • 8/2/2019 Dom by Kamalakar Dandu

    28/30

    Associating a Document with aSchema

    There are two ways to do that:

    1. With a schema declaration in theXML document.

    2. By specifying the schema(s) touse in the application.

  • 8/2/2019 Dom by Kamalakar Dandu

    29/30

    To specify the schema definition in

    the document, you would create

    XML like this:

    ...

    S f f

  • 8/2/2019 Dom by Kamalakar Dandu

    30/30

    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