Example usage for javax.xml.parsers DocumentBuilderFactory newDocumentBuilder

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

Introduction

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

Prototype


public abstract DocumentBuilder newDocumentBuilder() throws ParserConfigurationException;

Source Link

Document

Creates a new instance of a javax.xml.parsers.DocumentBuilder using the currently configured parameters.

Usage

From source file:Main.java

public static void main(String[] args)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//from   ww w .  j  a  v a 2s  .c  o m
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("books.xml");

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//numDocs");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue());
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from   w w w .ja va2 s.co  m*/

    DocumentBuilder loader = factory.newDocumentBuilder();
    Document document = loader.newDocument();
    edit(document);

    System.out.println(documentToString(document));

}

From source file:Main.java

public static void main(String argv[]) throws Exception {
    String next = "keyword,123";
    String[] input = next.split(",");

    String textToFind = input[0].replace("'", "\\'"); // "CEO";
    String textToReplace = input[1].replace("'", "\\'"); // "Chief Executive Officer";
    String filepath = "root.xml";
    String fileToBeSaved = "root2.xml";

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(filepath);

    XPath xpath = XPathFactory.newInstance().newXPath();
    // change ELEMENTS

    String xPathExpression = "//*[text()='" + textToFind + "']";
    NodeList nodes = (NodeList) xpath.evaluate(xPathExpression, doc, XPathConstants.NODESET);

    for (int idx = 0; idx < nodes.getLength(); idx++) {
        nodes.item(idx).setTextContent(textToReplace);
    }//from   w  ww  .ja  va 2  s  .c  o m

    // change ATTRIBUTES
    String xPathExpressionAttr = "//*/@*[.='" + textToFind + "']";
    NodeList nodesAttr = (NodeList) xpath.evaluate(xPathExpressionAttr, doc, XPathConstants.NODESET);

    for (int i = 0; i < nodesAttr.getLength(); i++) {
        nodesAttr.item(i).setTextContent(textToReplace);
    }
    System.out.println("Everything replaced.");

    // save xml file back
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(fileToBeSaved));
    transformer.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 w  w.ja  v a 2  s.  c  om*/
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");

    String attrValue = element.getAttribute("value");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from w ww. j a v  a2s.co  m
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    Element root = doc.createElementNS(null, "person"); // Create Root Element
    Element item = doc.createElementNS(null, "name"); // Create element
    item.appendChild(doc.createTextNode("Jeff"));
    root.appendChild(item); // Attach element to Root element
    item = doc.createElementNS(null, "age"); // Create another Element
    item.appendChild(doc.createTextNode("28"));
    root.appendChild(item); // Attach Element to previous element down tree
    item = doc.createElementNS(null, "height");
    item.appendChild(doc.createTextNode("1.80"));
    root.appendChild(item); // Attach another Element - grandaugther
    doc.appendChild(root); // Add Root to Document

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS");

    LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer
                                                       // for the DOM
    LSOutput out = domImplLS.createLSOutput();
    StringWriter stringOut = new StringWriter(); // Writer will be a String
    out.setCharacterStream(stringOut);
    ser.write(doc, out); // Serialize the DOM

    System.out.println("STRXML = " + stringOut.toString()); // DOM as a String
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);/*from   ww  w.ja va  2  s  .  com*/
    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 factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);//from ww w . j av  a 2 s.  c o  m

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager
            .getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb");

    ResultSet rs = con.createStatement().executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

    System.out.println(sw.toString());

    con.close();
    rs.close();
}

From source file:TestDOM.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.parse("zooinventory.xml");
    Element inventory = document.getDocumentElement();
    NodeList animals = inventory.getElementsByTagName("Animal");

    System.out.println("Animals = ");
    for (int i = 0; i < animals.getLength(); i++) {
        String name = DOMUtil.getSimpleElementText((Element) animals.item(i), "Name");
        String species = DOMUtil.getSimpleElementText((Element) animals.item(i), "Species");
        System.out.println("  " + name + " (" + species + ")");
    }/*  w w w .ja  v a2s  .co  m*/

    Element foodRecipe = DOMUtil.getFirstElement((Element) animals.item(1), "FoodRecipe");
    String name = DOMUtil.getSimpleElementText(foodRecipe, "Name");
    System.out.println("Recipe = " + name);
    NodeList ingredients = foodRecipe.getElementsByTagName("Ingredient");
    for (int i = 0; i < ingredients.getLength(); i++)
        System.out.println("  " + DOMUtil.getSimpleElementText((Element) ingredients.item(i)));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*  w w  w. jav a2 s  .c  o  m*/
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    NodeList list = doc.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
        Element element = (Element) list.item(i);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
    Document document = parser.parse(new File("NewFile.xml"));

    Schema schema = schemaFactory.newSchema(new File("NewFile.xsd"));
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(document));
}