Example usage for javax.xml.parsers DocumentBuilder parse

List of usage examples for javax.xml.parsers DocumentBuilder parse

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder parse.

Prototype


public abstract Document parse(InputSource is) throws SAXException, IOException;

Source Link

Document

Parse the content of the given input source as an XML document and return a new DOM Document object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(new InputSource(
            new StringReader("<emp><empname><firstName></firstName><lastName></lastName></empname></emp>")));
    NodeList customerNodes = doc.getElementsByTagName("empname");
    for (int i = 0; i < customerNodes.getLength(); i++) {
        NodeList children = customerNodes.item(i).getChildNodes();
        for (int j = 0; j < children.getLength(); j++) {
            String childNode = children.item(j).getNodeName();
            if (childNode.equalsIgnoreCase("firstName")) {
                children.item(j).setTextContent(String.valueOf("John"));
            } else if (childNode.equalsIgnoreCase("lastName")) {
                children.item(j).setTextContent(String.valueOf("Doe"));
            }//from   w  w w  .  ja  v  a2s.c  o  m
        }
    }
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    System.out.println(writer.getBuffer().toString());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new InputSource(new StringReader(cfgXml)));
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("config");
    for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        System.out.println("\nCurrent Element :" + nNode.getNodeName());
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            Config c = new Config();
            c.name = eElement.getAttribute("name");
            c.type = eElement.getAttribute("type");
            c.format = eElement.getAttribute("format");
            c.size = Integer.valueOf(eElement.getAttribute("size"));
            c.scale = Integer.valueOf(eElement.getAttribute("scale"));
            String attribute = eElement.getAttribute("required");
            c.required = Boolean.valueOf("Yes".equalsIgnoreCase(attribute) ? true : false);
            System.out.println("Imported config : " + c);
        }//from  w  w  w . ja v a 2s  .  co m
    }
}

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(new File("Table.xml"));

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath path = xFactory.newXPath();
    XPathExpression exp = path.compile("/tables/table");
    NodeList nlTables = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    for (int tblIndex = 0; tblIndex < nlTables.getLength(); tblIndex++) {
        Node table = nlTables.item(tblIndex);
        Node nAtt = table.getAttributes().getNamedItem("title");
        System.out.println(nAtt.getTextContent());
        exp = path.compile("headings/heading");
        NodeList nlHeaders = (NodeList) exp.evaluate(table, XPathConstants.NODESET);
        Set<String> headers = new HashSet<String>(25);
        for (int index = 0; index < nlHeaders.getLength(); index++) {
            headers.add(nlHeaders.item(index).getTextContent().trim());
        }/*  www. jav  a2s  .c o  m*/
        for (String header : headers) {
            System.out.println(header);
        }
        exp = path.compile("tablebody/tablerow");
        NodeList nlRows = (NodeList) exp.evaluate(table, XPathConstants.NODESET);
        for (int index = 0; index < nlRows.getLength(); index++) {
            Node rowNode = nlRows.item(index);
            exp = path.compile("tablecell/item");
            NodeList nlValues = (NodeList) exp.evaluate(rowNode, XPathConstants.NODESET);
            List<String> values = new ArrayList<String>(25);
            for (int valueIndex = 0; valueIndex < nlValues.getLength(); valueIndex++) {
                values.add(nlValues.item(valueIndex).getTextContent().trim());
            }
            for (String value : values) {
                System.out.println(value);
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setValidating(false);//from  w  ww .j a v a 2s. c om
    domFactory.setNamespaceAware(true);
    domFactory.setIgnoringComments(true);
    domFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("C:/data.xsd");

    Node rootNode = dDoc.getElementsByTagName("xs:schema").item(0);
    System.out.println(rootNode.getNodeName());

    XPath xPath1 = XPathFactory.newInstance().newXPath();
    NamespaceContext nsContext = new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            return "http://www.w3.org/2001/XMLSchema";
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return "xs";
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            Set s = new HashSet();
            s.add("xs");
            return s.iterator();
        }
    };
    xPath1.setNamespaceContext((NamespaceContext) nsContext);
    NodeList nList1 = (NodeList) xPath1.evaluate("//xs:schema", dDoc, XPathConstants.NODESET);
    System.out.println(nList1.item(0).getNodeName());

    NodeList nList2 = (NodeList) xPath1.evaluate("//xs:element", rootNode, XPathConstants.NODESET);
    System.out.println(nList2.item(0).getNodeName());
}

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);/*from   w  ww. j  a  v  a2s  .c  o  m*/
    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 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 w  w  . ja  v a2s  .  com*/

    // 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[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*  w  w w . ja v a2s. c o  m*/
    factory.setXIncludeAware(true);
    DocumentBuilder parser = factory.newDocumentBuilder();
    System.out.println("aware: " + parser.isXIncludeAware());
    Document document = parser.parse(args[0]);
    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 {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = docBuilderFactory.newDocumentBuilder();
    Document node = documentBuilder.parse(new FileInputStream("data.xml"));
    cleanEmptyTextNodes(node);//from   w  ww  .  j a  v  a  2s.c  om
    StreamResult result = new StreamResult(new StringWriter());

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

    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(4));

    transformer.transform(new DOMSource(node), result);
    System.out.println(result.getWriter().toString());
}

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(/*from  w  ww.jav  a2s.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[] args) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader("<root>\r\n" + //
            "<Users>\r\n" + //
            "   <App id=\"test\">\r\n" + //
            "      <Username>ADMIN</Username>\r\n" + //
            "      <Password>ADMIN</Password>\r\n" + //
            "   </App>\r\n" + //
            "</Users>\r\n" + //
            "<Users>\r\n" + //
            "   <App id=\"test2\">\r\n" + //
            "      <Username>ADMIN2</Username>\r\n" + //
            "      <Password>ADMIN2</Password>\r\n" + //
            "   </App>\r\n" + //
            "</Users>\r\n" + //
            "</root>")));
    String inputId = "test2";
    String xpathStr = "//Users/App[@id='" + inputId + "']";
    // retrieve elements and change their content
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(xpathStr + "/Username");
    Node username = (Node) expr.evaluate(doc, XPathConstants.NODE);
    username.setTextContent("test-username");
    expr = xpath.compile(xpathStr + "/Password");
    Node password = (Node) expr.evaluate(doc, XPathConstants.NODE);
    password.setTextContent("test-password");
    // output the document
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    System.out.println(writer.toString());

}