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[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = factory.newDocumentBuilder().parse(is);

    CDATASection cdataNode = doc.createCDATASection("");

    CharacterData cdata = cdataNode;

    cdata.appendData("from java2s.com");
    System.out.println(cdataNode);
    cdata.replaceData(1, 2, "new");
    System.out.println(cdataNode);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = factory.newDocumentBuilder().parse(is);

    CDATASection cdataNode = doc.createCDATASection("");

    CharacterData cdata = cdataNode;

    int offset = 0;
    cdata.insertData(offset, "a ");
    cdata.appendData(" b");
    System.out.println(cdataNode);
}

From source file:DOMGenerate.java

public static void main(String[] argv) {
    try {//from ww  w. j  a va 2 s  .  c  o  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        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()); // Spit out the
                                                                // DOM as a String
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

License:asdf

public static void main(String[] args) throws Exception {
    String xml = "<soapenv:Envelope " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
            + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
            + "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
            + "xmlns:ser=\"http://services.web.post.list.com\"><soapenv:Header>"
            + "<authInfo xsi:type=\"soap:authentication\" "
            + "xmlns:soap=\"http://list.com/services/SoapRequestProcessor\">"
            + "<username xsi:type=\"xsd:string\">asdf@g.com</username>"
            + "<password xsi:type=\"xsd:string\">asdf</password></authInfo></soapenv:Header></soapenv:Envelope>";
    System.out.println(xml);//w w  w  . ja  v  a2 s . c om
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xml)));
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        @Override
        public Iterator getPrefixes(String arg0) {
            return null;
        }

        @Override
        public String getPrefix(String arg0) {
            return null;
        }

        @Override
        public String getNamespaceURI(String arg0) {
            if ("soapenv".equals(arg0)) {
                return "http://schemas.xmlsoap.org/soap/envelope/";
            }
            return null;
        }
    });
    XPathExpression expr = xpath.compile("/soapenv:Envelope/soapenv:Header/authInfo/password");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    System.out.println("Got " + nodes.getLength() + " nodes");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

    SOAPHeader soapHeader = soapEnvelope.getHeader();
    SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
            "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addAttribute(// w w w. ja  v  a  2s.  co  m
            soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
            "Body");
    Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
    SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

    Source source = soapPart.getContent();

    Node root = null;
    if (source instanceof DOMSource) {
        root = ((DOMSource) source).getNode();
    } else if (source instanceof SAXSource) {
        InputSource inSource = ((SAXSource) source).getInputSource();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = null;

        db = dbf.newDocumentBuilder();

        Document doc = db.parse(inSource);
        root = (Node) doc.getDocumentElement();
    }
}

From source file:Main.java

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

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

    Map entityValues = new HashMap();
    getEntityValues(doc, entityValues);

    NamedNodeMap entities = doc.getDoctype().getEntities();
    for (int i = 0; i < entities.getLength(); i++) {
        Entity entity = (Entity) entities.item(i);
        System.out.println(entity);
        String entityName = entity.getNodeName();
        System.out.println(entityName);
        String entityPublicId = entity.getPublicId();
        System.out.println(entityPublicId);
        String entitySystemId = entity.getSystemId();
        System.out.println(entitySystemId);
        Node entityValue = (Node) entityValues.get(entityName);
        System.out.println(entityValue);
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

    SOAPHeader soapHeader = soapEnvelope.getHeader();
    SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
            "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addAttribute(//  w  ww  .j a  va2 s .c  o m
            soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
            "Body");
    Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
    SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

    Source source = soapPart.getContent();

    Node root = null;
    if (source instanceof DOMSource) {
        root = ((DOMSource) source).getNode();
    } else if (source instanceof SAXSource) {
        InputSource inSource = ((SAXSource) source).getInputSource();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = null;

        db = dbf.newDocumentBuilder();

        Document doc = db.parse(inSource);
        root = (Node) doc.getDocumentElement();
    }

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(new DOMSource(root), new StreamResult(System.out));
}

From source file:DOMCheck.java

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

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(validate);/*from   w  w w.  j  ava  2  s . c o 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);// w w  w  .j  ava2s  .  c om

    factory.setExpandEntityReferences(false);

    Document doc1 = factory.newDocumentBuilder().parse(new File("filename"));
    NodeList list = doc1.getElementsByTagName("entry");
    Element element = (Element) list.item(0);

    Document doc2 = factory.newDocumentBuilder().parse(new File("infilename2.xml"));

    // Make a copy of the element subtree suitable for inserting into doc2
    Node node = doc2.importNode(element, true);

    // Get the parent
    Node parent = node.getParentNode();

    // Get children
    NodeList children = node.getChildNodes();

    // Get first child; null if no children
    Node child = node.getFirstChild();

    // Get last child; null if no children
    child = node.getLastChild();

    // Get next sibling; null if node is last child
    Node sibling = node.getNextSibling();

    // Get previous sibling; null if node is first child
    sibling = node.getPreviousSibling();

    // Get first sibling
    sibling = node.getParentNode().getFirstChild();

    // Get last sibling
    sibling = node.getParentNode().getLastChild();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w  ww .java  2  s. co m*/
    DocumentBuilder builder;
    Document doc = null;
    builder = factory.newDocumentBuilder();
    doc = builder.parse("employees.xml");
    // Create XPathFactory object
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // Create XPath object
    XPath xpath = xpathFactory.newXPath();
    String name = getEmployeeNameById(doc, xpath, 4);
    System.out.println("Employee Name with ID 4: " + name);

    List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
    System.out.println("Employees with 'age>30' are:" + Arrays.toString(names.toArray()));

    List<String> femaleEmps = getFemaleEmployeesName(doc, xpath);
    System.out.println("Female Employees names are:" + Arrays.toString(femaleEmps.toArray()));
}