Example usage for javax.xml.parsers DocumentBuilderFactory newInstance

List of usage examples for javax.xml.parsers DocumentBuilderFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory newInstance.

Prototype

public static DocumentBuilderFactory newInstance() 

Source Link

Document

Obtain a new instance of a DocumentBuilderFactory .

Usage

From source file:XMLInfo.java

public static void main(String args[]) {
    try {//from  w w w  . ja  va 2  s  . c om
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse("xmlFileName.xml");
        Node root = document.getDocumentElement();
        System.out.print("Here is the document's root node:");
        System.out.println(" " + root.getNodeName());
        System.out.println("Here are its child elements: ");
        NodeList childNodes = root.getChildNodes();
        Node currentNode;

        for (int i = 0; i < childNodes.getLength(); i++) {
            currentNode = childNodes.item(i);
            System.out.println(currentNode.getNodeName());
        }

        // get first child of root element
        currentNode = root.getFirstChild();

        System.out.print("The first child of root node is: ");
        System.out.println(currentNode.getNodeName());

        // get next sibling of first child
        System.out.print("whose next sibling is: ");
        currentNode = currentNode.getNextSibling();
        System.out.println(currentNode.getNodeName());

        // print value of next sibling of first child
        System.out.println("value of " + currentNode.getNodeName() + " element is: "
                + currentNode.getFirstChild().getNodeValue());

        // print name of parent of next sibling of first child
        System.out.print("Parent node of " + currentNode.getNodeName() + " is: "
                + currentNode.getParentNode().getNodeName());
    }
    // handle exception creating DocumentBuilder
    catch (ParserConfigurationException parserError) {
        System.err.println("Parser Configuration Error");
        parserError.printStackTrace();
    }

    // handle exception reading data from file
    catch (IOException fileException) {
        System.err.println("File IO Error");
        fileException.printStackTrace();
    }

    // handle exception parsing XML document
    catch (SAXException parseException) {
        System.err.println("Error Parsing Document");
        parseException.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = Factory.newDocumentBuilder();
    Document doc = builder.parse("myxml.xml");
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    XPathExpression expr = xpath.compile("//" + "item1" + "/*");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        Element el = (Element) nodes.item(i);
        System.out.println("tag: " + el.getNodeName());
        if (el.getFirstChild().getNodeType() == Node.TEXT_NODE)
            System.out.println("inner value:" + el.getFirstChild().getNodeValue());

        NodeList children = el.getChildNodes();
        for (int k = 0; k < children.getLength(); k++) {
            Node child = children.item(k);
            if (child.getNodeType() != Node.TEXT_NODE) {
                System.out.println("child tag: " + child.getNodeName());
                if (child.getFirstChild().getNodeType() == Node.TEXT_NODE)
                    System.out.println("inner child value:" + child.getFirstChild().getNodeValue());
            }//from   ww  w  .  ja  va  2s  .co  m
        }
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*from w w w.j av a  2  s  .com*/

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Source source = new DOMSource(doc);

    URI uri = new File("infilename.xml").toURI();
    source.setSystemId(uri.toString());

    DefaultHandler handler = new MyHandler();
    SAXResult result = new SAXResult(handler);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
}

From source file:PrintDOM.java

public static void main(String[] args) throws Exception {
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = parser.parse(new InputSource("zooinventory.xml"));
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    Source source = new DOMSource(document);
    Result output = new StreamResult(System.out);
    transformer.transform(source, output);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    userdom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = userdom.createElement("users");
    Node adoptNode = userdom.adoptNode(root);
    userdom.appendChild(adoptNode);//from   w w w .ja  va  2 s.  com
    Element e = userdom.createElement("user");

    e.setAttribute("id", "blah");
    e.setAttribute("username", "kermit");
    e.setAttribute("password", "bunnies in the air");
    e.setAttribute("login", "kermmi");

    userdom.getFirstChild().appendChild(e);
    System.out.println(e);
    System.out.println(userdom.getFirstChild() + "|" + userdom.getFirstChild().getFirstChild());
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    System.out.println(userdom.getFirstChild() + "|" + userdom.getFirstChild().getFirstChild());
    DOMSource ds = new DOMSource(userdom);

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        StreamResult sr = new StreamResult(baos);
        trans.transform(ds, sr);
        System.out.println(new String(baos.toByteArray()));
    }
}

From source file:DOMCheck.java

static public void main(String[] arg) {
    boolean validate = true;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(validate);// w  w w .  java  2  s  . co m
    dbf.setNamespaceAware(true);

    try {
        DocumentBuilder builder = dbf.newDocumentBuilder();
        builder.setErrorHandler(new MyErrorHandler());
        InputSource is = new InputSource("person.xml");
        Document doc = builder.parse(is);
    } catch (SAXException e) {
        System.out.println(e);
    } catch (ParserConfigurationException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*from   w  ww .ja  v  a2 s . c o  m*/

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();

    xformer.setOutputProperty(OutputKeys.METHOD, "text");

    Source source = new DOMSource(doc);
    Result result = new StreamResult(new File("outfilename.xml"));
    xformer.transform(source, result);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);//from w ww.jav a  2s .c o  m

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();

    xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "publicId");
    xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "systemId");

    Source source = new DOMSource(doc);
    Result result = new StreamResult(new File("outfilename.xml"));
    xformer.transform(source, result);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);/*from  w  w w . j a v a 2 s  .co  m*/
    DocumentBuilder builder;
    builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(CFG_FILE);
    XPathExpression expr = XPathFactory.newInstance().newXPath().compile(XPATH_FOR_PRM_MaxThread);
    Object result = expr.evaluate(doc, XPathConstants.NUMBER);
    if (result instanceof Double) {
        System.out.println(((Double) result).intValue());
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//from  w  ww  .j a  va2  s. c  o  m
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("c:\\file.xml");
    XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new UniversalNamespaceResolver(dDoc));
    String query = "//rss/channel/yweather:location/@city";
    XPathExpression expr = xPath.compile(query);
    Object result = expr.evaluate(dDoc, XPathConstants.STRING);
    System.out.println(result);
}