Example usage for org.w3c.dom Document getDocumentElement

List of usage examples for org.w3c.dom Document getDocumentElement

Introduction

In this page you can find the example usage for org.w3c.dom Document getDocumentElement.

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:Main.java

public static Element loadDocument(String location) {
    Document doc = null;
    try {/*ww w. j a va 2s  . co  m*/
        URL url = new URL(location);
        InputSource xmlInp = new InputSource(url.openStream());

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
        doc = parser.parse(xmlInp);
        Element root = doc.getDocumentElement();
        root.normalize();
        return root;
    } catch (SAXParseException err) {
        System.err.println("URLMappingsXmlDAO ** Parsing error" + ", line " + err.getLineNumber() + ", uri "
                + err.getSystemId());
        System.err.println("URLMappingsXmlDAO error: " + err.getMessage());
    } catch (SAXException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (java.net.MalformedURLException mfx) {
        System.err.println("URLMappingsXmlDAO error: " + mfx);
    } catch (java.io.IOException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (Exception pce) {
        System.err.println("URLMappingsXmlDAO error: " + pce);
    }
    return null;
}

From source file:Main.java

/**
 * Performs the actual recursive dumping of a DOM tree to a given
 * <CODE>PrintStream</CODE>. Note that dump is intended to be a detailed
 * debugging aid rather than pretty to look at. 
 * // w  w  w .j a  v a 2s . c  o  m
 * @param    out            The <CODE>PrintStream</CODE> to write to.
 * @param    node         The <CODE>Node</CODE> under consideration.
 * @param    indent         The level of indentation.
 * @see      #dump(Node)
 * @see      #dump(PrintStream, Node)
 * @since   TFP 1.0
 */
private static void doDump(PrintStream out, final Node node, int indent) {
    if (node != null) {
        for (int index = 0; index < indent; ++index)
            out.write(' ');

        switch (node.getNodeType()) {
        case Node.DOCUMENT_NODE: {
            Document document = (Document) node;

            out.println("DOCUMENT:");

            doDump(out, document.getDoctype(), indent + 1);
            doDump(out, document.getDocumentElement(), indent + 1);
            break;
        }

        case Node.DOCUMENT_TYPE_NODE: {
            DocumentType type = (DocumentType) node;

            out.println("DOCTYPE: [" + "name=" + format(type.getName()) + "," + "publicId="
                    + format(type.getPublicId()) + "," + "systemId=" + format(type.getSystemId()) + "]");
            break;
        }

        case Node.ELEMENT_NODE: {
            Element element = (Element) node;

            out.println("ELEMENT: [" + "ns=" + format(element.getNamespaceURI()) + "," + "name="
                    + format(element.getLocalName()) + "]");

            NamedNodeMap attrs = element.getAttributes();

            for (int index = 0; index < attrs.getLength(); ++index)
                doDump(out, attrs.item(index), indent + 1);

            for (Node child = element.getFirstChild(); child != null;) {
                doDump(out, child, indent + 1);
                child = child.getNextSibling();
            }
            break;
        }
        case Node.ATTRIBUTE_NODE: {
            Attr attr = (Attr) node;

            out.println("ATTRIBUTE: [" + "ns=" + format(attr.getNamespaceURI()) + "," + "prefix="
                    + format(attr.getPrefix()) + "," + "name=" + format(attr.getLocalName()) + "," + "value="
                    + format(attr.getNodeValue()) + "]");
            break;
        }

        case Node.TEXT_NODE: {
            Text text = (Text) node;

            out.println("TEXT: [" + format(text.getNodeValue()) + "]");

            for (Node child = text.getFirstChild(); child != null;) {
                doDump(out, child, indent + 1);
                child = child.getNextSibling();
            }
            break;
        }

        case Node.CDATA_SECTION_NODE: {
            CDATASection data = (CDATASection) node;

            out.println("CDATA: [" + format(data.getNodeValue()) + "]");
            break;
        }

        case Node.COMMENT_NODE: {
            Comment comm = (Comment) node;

            out.println("COMMENT: [" + format(comm.getNodeValue()) + "]");
            break;
        }

        default:
            out.println("UNKNOWN: [type=" + node.getNodeType() + "]");
            break;
        }
    }
}

From source file:Main.java

/**
 * Performs the actual recursive dumping of a DOM tree to a given
 * <CODE>PrintWriter</CODE>. Note that dump is intended to be a detailed
 * debugging aid rather than pretty to look at. 
 * //from   ww  w.  j  av a2 s .co m
 * @param    out            The <CODE>PrintWriter</CODE> to write to.
 * @param    node         The <CODE>Node</CODE> under consideration.
 * @param    indent         The level of indentation.
 * @see      #dump(PrintWriter, Node)
 * @since   TFP 1.0
 */
private static void doDump(PrintWriter out, final Node node, int indent) {
    if (node != null) {
        for (int index = 0; index < indent; ++index)
            out.write(' ');

        switch (node.getNodeType()) {
        case Node.DOCUMENT_NODE: {
            Document document = (Document) node;

            out.println("DOCUMENT:");

            doDump(out, document.getDoctype(), indent + 1);
            doDump(out, document.getDocumentElement(), indent + 1);
            break;
        }

        case Node.DOCUMENT_TYPE_NODE: {
            DocumentType type = (DocumentType) node;

            out.println("DOCTYPE: [" + "name=" + format(type.getName()) + "," + "publicId="
                    + format(type.getPublicId()) + "," + "systemId=" + format(type.getSystemId()) + "]");
            break;
        }

        case Node.ELEMENT_NODE: {
            Element element = (Element) node;

            out.println("ELEMENT: [" + "ns=" + format(element.getNamespaceURI()) + "," + "name="
                    + format(element.getLocalName()) + "]");

            NamedNodeMap attrs = element.getAttributes();

            for (int index = 0; index < attrs.getLength(); ++index)
                doDump(out, attrs.item(index), indent + 1);

            for (Node child = element.getFirstChild(); child != null;) {
                doDump(out, child, indent + 1);
                child = child.getNextSibling();
            }
            break;
        }
        case Node.ATTRIBUTE_NODE: {
            Attr attr = (Attr) node;

            out.println("ATTRIBUTE: [" + "ns=" + format(attr.getNamespaceURI()) + "," + "prefix="
                    + format(attr.getPrefix()) + "," + "name=" + format(attr.getLocalName()) + "," + "value="
                    + format(attr.getNodeValue()) + "]");
            break;
        }

        case Node.TEXT_NODE: {
            Text text = (Text) node;

            out.println("TEXT: [" + format(text.getNodeValue()) + "]");

            for (Node child = text.getFirstChild(); child != null;) {
                doDump(out, child, indent + 1);
                child = child.getNextSibling();
            }
            break;
        }

        case Node.CDATA_SECTION_NODE: {
            CDATASection data = (CDATASection) node;

            out.println("CDATA: [" + format(data.getNodeValue()) + "]");
            break;
        }

        case Node.COMMENT_NODE: {
            Comment comm = (Comment) node;

            out.println("COMMENT: [" + format(comm.getNodeValue()) + "]");
            break;
        }

        default:
            out.println("UNKNOWN: [type=" + node.getNodeType() + "]");
            break;
        }
    }
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

/**
 * Transforms a string representation of an XML Node to an Node
 *
 * @param value    the node as String//from  w w w .j a  va  2  s  .  co m
 * @param features parsing features to set on the document builder
 * @return the Node object
 * @throws Exception in case the String can't be represented as a Node
 */
public static Node stringToNode(String value, String encoding, String features) throws Exception {
    Node node;
    if (StringUtils.isEmpty(encoding)) {
        encoding = "UTF-8";
    }
    try (InputStream inputStream = new ByteArrayInputStream(value.getBytes(encoding))) {
        // check if input value is a Node
        Document docNew = DocumentUtils.createDocumentBuilder(features).parse(inputStream);
        node = docNew.getDocumentElement();
    } catch (SAXException se) {
        throw new Exception("Value " + value + "is not valid XML element : " + se.getMessage());
    }
    return node;
}

From source file:Main.java

public static Document read(String filename) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);/*  w  w w .  jav a2s .com*/
    DocumentBuilder builder = null;
    Document document = null;
    try {
        builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }
        });
        document = builder.parse(new File(filename));
        document.getDocumentElement().normalize();
    } catch (Exception e) {
    }
    return document;
}

From source file:Main.java

/**
 * Locates the element defined by the XPath expression in the XML file and replaces the child text with the passed value.
 * @param fileName The XML file to update.
 * @param xPathExpression An XPath expression that locates the element to update.
 * @param value The value to update the attribute to.
 *///from  w  w  w.  ja  v  a  2  s. c o m
public static void updateElementValueInXMLFile(String fileName, String xPathExpression, String value) {
    try {
        Document document = parseXML(new File(fileName));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xpathExpression = xpath.compile(xPathExpression);
        Element element = (Element) xpathExpression.evaluate(document, NODE);
        element.getFirstChild().setNodeValue(value);
        writeElement(document.getDocumentElement(), fileName);
    } catch (Exception e) {
        throw new RuntimeException("Failed to extract element from:" + fileName, e);
    }
}

From source file:at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient.java

private static Element sendSOAPRequest(String webServiceURL, Element request) throws MISSimpleClientException {

    //      try {
    //         System.out.println("REQUEST-MIS: \n"  + DOMUtils.serializeNode(request));
    //      } catch (TransformerException e1) {
    //         e1.printStackTrace();
    //      } catch (IOException e1) {
    //         e1.printStackTrace();
    //      }// w  w w  .  java 2s .c o  m

    if (webServiceURL == null) {
        throw new NullPointerException("Argument webServiceURL must not be null.");
    }
    if (request == null) {
        throw new NullPointerException("Argument request must not be null.");
    }
    try {
        HttpClient httpclient = HttpClientWithProxySupport.getHttpClient();
        PostMethod post = new PostMethod(webServiceURL);
        StringRequestEntity re = new StringRequestEntity(DOMUtils.serializeNode(packIntoSOAP(request)),
                "text/xml", "UTF-8");
        post.setRequestEntity(re);
        int responseCode = httpclient.executeMethod(post);

        if (responseCode != 200) {
            throw new MISSimpleClientException("Invalid HTTP response code " + responseCode);
        }
        //Element elem = parse(post.getResponseBodyAsStream());
        Document doc = DOMUtils.parseDocumentSimple(post.getResponseBodyAsStream());
        return unpackFromSOAP(doc.getDocumentElement());

    } catch (IOException e) {
        throw new MISSimpleClientException("service.04", e);

    } catch (TransformerException e) {
        throw new MISSimpleClientException("service.06", e);

    } catch (SAXException e) {
        throw new MISSimpleClientException("service.06", e);

    } catch (ParserConfigurationException e) {
        throw new MISSimpleClientException("service.06", e);

    } catch (Exception e) {
        throw new MISSimpleClientException("service.06", e);

    }

}

From source file:com.netsteadfast.greenstep.util.BusinessProcessManagementUtils.java

public static String getResourceProcessId(File activitiBpmnFile) throws Exception {
    if (null == activitiBpmnFile || !activitiBpmnFile.exists()) {
        throw new Exception("file no exists!");
    }//ww w.j  av  a  2 s  . co  m
    if (!activitiBpmnFile.getName().endsWith(_SUB_NAME)) {
        throw new Exception("not resource file.");
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(activitiBpmnFile);
    Element element = doc.getDocumentElement();
    if (!"definitions".equals(element.getNodeName())) {
        throw new Exception("not resource file.");
    }
    String processId = activitiBpmnFile.getName();
    if (processId.endsWith(_SUB_NAME)) {
        processId = processId.substring(0, processId.length() - _SUB_NAME.length());
    }
    NodeList nodes = element.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if ("process".equals(node.getNodeName())) {
            NamedNodeMap nodeMap = node.getAttributes();
            for (int attr = 0; attr < nodeMap.getLength(); attr++) {
                Node processAttr = nodeMap.item(attr);
                if ("id".equals(processAttr.getNodeName())) {
                    processId = processAttr.getNodeValue();
                }
            }
        }
    }
    return processId;
}

From source file:Main.java

public static String qualifyName(Document doc, String name) {

    // parse name into local name and prefix pre:local
    int idx = name.indexOf(":");
    String localName = name;//from   w w  w. j  av  a  2 s.com
    String pre = null;
    if (idx != -1 && idx > 0) {
        localName = name.substring(idx + 1);
        pre = name.substring(0, idx);
    }

    // if no prefix was specified we use document namespaceURI
    if (pre == null) {
        String ns = doc.getDocumentElement().getAttribute("targetNamespace");
        if (ns == null || "".equals(ns)) {
            return doc.getDocumentElement().getNamespaceURI() + ":" + localName;
        } else {
            return ns + ":" + localName;
        }
    }

    // resolve prefix into namespace URI
    String ns = doc.getDocumentElement().getAttribute("xmlns:" + pre);
    if (ns == null || "".equals(ns)) {
        throw new RuntimeException("Bad namespace specified in " + name);
    }

    return ns + ":" + localName;
}

From source file:com.hp.test.framework.generatejellytess.GenerateJellyTests.java

public static Map<String, String> GetLocators(String Testcases_path) {
    //   ReadTestCases.verfiy=verification;
    try {//from   w  ww . ja va 2s.c om
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        // deletes file when the virtual machine terminate
        doc = documentBuilder.parse(new File(Testcases_path));
        //   doc = documentBuilder.parse(f);
        getData(null, doc.getDocumentElement());
        //   System.out.println("purush");

    } catch (Exception exe) {
        log.error("Error in getting locators" + exe.getMessage());
    }
    Map<String, List<String>> actions_exp = new HashMap<String, List<String>>();

    return Locators;

}