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 void vectorToXML222(String xmlFile, String xpath, String parentNodeName, Vector<HashMap> vector) {
    File file = new File(xmlFile);
    try {//from   w  ww  .j  a  v  a 2  s.  c  o  m
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document document;
        Element rootNode;
        if (file.exists()) {
            document = documentBuilder.parse(new File(xmlFile));
            rootNode = document.getDocumentElement();
        } else {
            document = documentBuilder.newDocument();
            rootNode = document.createElement(xpath);
            document.appendChild(rootNode);
        }

        for (int x = 0; x < vector.size(); x++) {
            Element parentNode = document.createElement(parentNodeName);
            rootNode.appendChild(parentNode);
            HashMap hashmap = vector.get(x);
            Set set = hashmap.entrySet();
            Iterator i = set.iterator();

            while (i.hasNext()) {
                Map.Entry me = (Map.Entry) i.next();
                // System.out.println("key=" +
                // me.getKey().toString());
                Element em = document.createElement(me.getKey().toString());
                em.appendChild(document.createTextNode(me.getValue().toString()));
                parentNode.appendChild(em);
                // System.out.println("write " +
                // me.getKey().toString() +
                // "="
                // + me.getValue().toString());
            }
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        FileOutputStream fo = new FileOutputStream(xmlFile);
        StreamResult result = new StreamResult(fo);
        transformer.transform(source, result);
    } catch (Exception ex) {
        file.delete();
        ex.printStackTrace();
    }
}

From source file:edu.indiana.d2i.datacatalog.dashboard.api.USStates.java

public static String getStates(String statesFilePath)
        throws ParserConfigurationException, IOException, SAXException {
    JSONObject statesFeatureCollection = new JSONObject();
    statesFeatureCollection.put("type", "FeatureCollection");
    JSONArray features = new JSONArray();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    try {/*from   w  w  w  .j  a  v a2 s .  com*/
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document dom = documentBuilder.parse(new FileInputStream(new File(statesFilePath)));
        Element docElement = dom.getDocumentElement();
        NodeList states = docElement.getElementsByTagName("state");
        for (int i = 0; i < states.getLength(); i++) {
            Node state = states.item(i);
            JSONObject stateObj = new JSONObject();
            stateObj.put("type", "Feature");
            JSONObject geometry = new JSONObject();
            geometry.put("type", "Polygon");
            JSONArray coordinates = new JSONArray();
            JSONArray coordinateSub = new JSONArray();
            NodeList points = ((Element) state).getElementsByTagName("point");
            for (int j = 0; j < points.getLength(); j++) {
                Node point = points.item(j);
                JSONArray pointObj = new JSONArray();
                float lat = Float.parseFloat(((Element) point).getAttribute("lat"));
                float lng = Float.parseFloat(((Element) point).getAttribute("lng"));
                double trLng = lng * 20037508.34 / 180;
                double trLat = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
                pointObj.add(lng);
                pointObj.add(lat);
                coordinateSub.add(pointObj);
            }
            geometry.put("coordinates", coordinates);
            coordinates.add(coordinateSub);
            stateObj.put("geometry", geometry);
            JSONObject name = new JSONObject();
            name.put("Name", ((Element) state).getAttribute("name"));
            name.put("colour", "#FFF901");
            stateObj.put("properties", name);
            features.add(stateObj);
        }
        statesFeatureCollection.put("features", features);
        return statesFeatureCollection.toJSONString();
    } catch (ParserConfigurationException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (FileNotFoundException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (SAXException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (IOException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    }
}

From source file:Main.java

public static Element GetXmlDocFromStr(String xmlStr) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;/*from  ww w  . ja  v a 2 s.com*/
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }
    Document doc = null;
    try {
        InputStream inputStream = new ByteArrayInputStream(xmlStr.getBytes());
        doc = db.parse(inputStream);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (Element) doc.getDocumentElement();
}

From source file:com.cloud.test.utils.UtilsForTest.java

public static Map<String, String> getSingleValueFromXML(InputStream is, String[] tagNames) {
    Map<String, String> returnValues = new HashMap<String, String>();
    try {/*w ww  .  j av  a 2  s  . c  o m*/
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(is);
        Element rootElement = doc.getDocumentElement();

        for (int i = 0; i < tagNames.length; i++) {
            NodeList targetNodes = rootElement.getElementsByTagName(tagNames[i]);
            if (targetNodes.getLength() <= 0) {
                System.out.println("no " + tagNames[i] + " tag in XML response...returning null");
            } else {
                returnValues.put(tagNames[i], targetNodes.item(0).getTextContent());
            }
        }
    } catch (Exception ex) {
        System.out.println("error processing XML");
        ex.printStackTrace();
    }
    return returnValues;
}

From source file:com.cloud.test.utils.UtilsForTest.java

public static Map<String, String> parseXML(InputStream is, String[] tagNames) {
    Map<String, String> returnValues = new HashMap<String, String>();
    try {/*from  ww  w . jav a 2  s  .  c  o m*/
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(is);
        Element rootElement = doc.getDocumentElement();

        for (int i = 0; i < tagNames.length; i++) {
            NodeList targetNodes = rootElement.getElementsByTagName(tagNames[i]);
            if (targetNodes.getLength() <= 0) {
                System.out.println("no " + tagNames[i] + " tag in the response");
                returnValues.put(tagNames[i], null);
            } else {
                returnValues.put(tagNames[i], targetNodes.item(0).getTextContent());
            }
        }
    } catch (Exception ex) {
        System.out.println("error processing XML");
        ex.printStackTrace();
    }
    return returnValues;
}

From source file:Main.java

/**
 *
 * @param document// w w  w  . j  a va  2 s .c  o  m
 * @param tagName
 * @return
 */
public static String getTagValueAsString(Document document, String tagName) {
    if (document == null || tagName == null || tagName.length() == 0)
        return null;

    String tagValue = null;
    NodeList nlist = null;
    Element element = null;

    Element root = document.getDocumentElement();

    nlist = root.getElementsByTagName(tagName);
    element = (Element) nlist.item(0);
    if (element.hasChildNodes()) {
        tagValue = element.getFirstChild().getNodeValue();
    }
    return tagValue;
}

From source file:com.cloud.test.utils.UtilsForTest.java

public static Map<String, List<String>> getMultipleValuesFromXML(InputStream is, String[] tagNames) {
    Map<String, List<String>> returnValues = new HashMap<String, List<String>>();
    try {//from w  w  w  . j  a v a2  s .c o  m
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(is);
        Element rootElement = doc.getDocumentElement();
        for (int i = 0; i < tagNames.length; i++) {
            NodeList targetNodes = rootElement.getElementsByTagName(tagNames[i]);
            if (targetNodes.getLength() <= 0) {
                System.out.println("no " + tagNames[i] + " tag in XML response...returning null");
            } else {
                List<String> valueList = new ArrayList<String>();
                for (int j = 0; j < targetNodes.getLength(); j++) {
                    Node node = targetNodes.item(j);
                    valueList.add(node.getTextContent());
                }
                returnValues.put(tagNames[i], valueList);
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return returnValues;
}

From source file:eu.serco.dhus.xml.parser.TaskTableParser.java

public static TaskTable parseTaskTable(String filename)
        throws ParserConfigurationException, SAXException, IOException {

    TaskTable taskTable = new TaskTable();

    if (filename == null || filename.isEmpty())
        throw new RuntimeException("The name of the XML file is required!");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    // Load the input XML document, parse it and return an instance of the
    // Document class.
    Document document = builder.parse(new File(filename));
    document.getDocumentElement().normalize();
    NodeList list = document.getElementsByTagName("Processor_Name");
    logger.info(" NodeList list size----: " + list.getLength());
    if (list != null && list.item(0) != null && list.item(0).getFirstChild() != null) {
        taskTable.setProcessorName(list.item(0).getFirstChild().getNodeValue());
    }/*from w  w w. j  ava2 s  .  c o m*/

    NodeList nodeList = document.getElementsByTagName("Task");
    Node node;
    Element elem;
    List<Task> tasks = new ArrayList<Task>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Task task = new Task();
        node = nodeList.item(i);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            elem = (Element) node;

            task.setName(elem.getElementsByTagName("Name").item(0).getChildNodes().item(0).getNodeValue());
            logger.info("taskname:  " + task.getName());

            List<Input> task_inputs = new ArrayList<Input>();
            NodeList inputs = elem.getElementsByTagName("Input");

            for (int j = 0; j < inputs.getLength(); j++) {

                Input input = new Input();
                node = inputs.item(j);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    elem = (Element) node;

                    input.setMode(
                            elem.getElementsByTagName("Mode").item(0).getChildNodes().item(0).getNodeValue());
                    logger.info("==== mode:  " + input.getMode());
                    input.setMandatory(elem.getElementsByTagName("Mandatory").item(0).getChildNodes().item(0)
                            .getNodeValue());
                    logger.info("==== mandatory:  " + input.getMandatory());

                    List<Alternative> input_alternatives = new ArrayList<Alternative>();
                    NodeList alternatives = elem.getElementsByTagName("Alternative");

                    for (int k = 0; k < alternatives.getLength(); k++) {

                        Alternative alternative = new Alternative();
                        node = alternatives.item(k);

                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            elem = (Element) node;

                            alternative.setOrder(Integer.parseInt(elem.getElementsByTagName("Order").item(0)
                                    .getChildNodes().item(0).getNodeValue()));
                            logger.info("==== order:  " + alternative.getOrder());
                            alternative.setRetrievalMode(elem.getElementsByTagName("Retrieval_Mode").item(0)
                                    .getChildNodes().item(0).getNodeValue());
                            logger.info("==== retrievalMode:  " + alternative.getRetrievalMode());
                            alternative.setT0(Double.parseDouble(elem.getElementsByTagName("T0").item(0)
                                    .getChildNodes().item(0).getNodeValue()));
                            logger.info("==== t0:  " + alternative.getT0());
                            alternative.setT1(Double.parseDouble(elem.getElementsByTagName("T1").item(0)
                                    .getChildNodes().item(0).getNodeValue()));
                            logger.info("==== t1:  " + alternative.getT1());
                            alternative.setFileType(elem.getElementsByTagName("File_Type").item(0)
                                    .getChildNodes().item(0).getNodeValue());
                            logger.info("==== fileType:  " + alternative.getFileType());
                            alternative.setFileNameType(elem.getElementsByTagName("File_Name_Type").item(0)
                                    .getChildNodes().item(0).getNodeValue());
                            logger.info("==== fileNameType:  " + alternative.getFileNameType());
                        }
                        input_alternatives.add(alternative);
                    }
                    input.setAlternatives(input_alternatives);
                }
                task_inputs.add(input);
            }
            task.setInputs(task_inputs);
        }
        tasks.add(task);
    }
    taskTable.setTasks(tasks);
    return taskTable;
}

From source file:Main.java

/**
 * Will create a documentFragment of the replacingDocument, will import the
 * replacingDocument as a node of the replacedDocument, and then will
 * replace the replaceNode with the documentFragment of replacingDocument.
 * /*from www . j av  a2s  .  co  m*/
 * @param replacedDocument
 *            The document which will have a node replace
 * @param replacingDocument
 *            The document that will replace a node
 * @param replacedNode
 *            The node in replacedDocument that will be replaced
 * @return The new version of replacedDocument will replacedNode replaced
 */
public static Node replaceNode(final Document replacedDocument, final Document replacingDocument,
        final Node replacedNode) {

    // Create a documentFragment of the replacingDocument
    DocumentFragment docFrag = replacingDocument.createDocumentFragment();
    Element rootElement = replacingDocument.getDocumentElement();
    docFrag.appendChild(rootElement);

    // Import docFrag under the ownership of replacedDocument
    Node replacingNode = ((replacedDocument).importNode(docFrag, true));

    // In order to replace the node need to retrieve replacedNode's parent
    Node replaceNodeParent = replacedNode.getParentNode();
    replaceNodeParent.replaceChild(replacingNode, replacedNode);
    return replacedDocument;
}

From source file:com.bluexml.xforms.actions.EnumAction.java

private static void fillValues(String type, Document doc) {
    Element root = doc.getDocumentElement();

    Map<String, String> values = new HashMap<String, String>();
    Map<String, String> keys = new HashMap<String, String>();

    NodeList childNodes = root.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        if (child instanceof Element) {
            Element element = (Element) child;
            addValue(element, values, keys);
        }//w w w.j  a va  2s.  c o  m
    }

    enumValues.put(type, values);
    enumKeys.put(type, keys);
}