Example usage for org.w3c.dom Document getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:Main.java

public static String getAttribute(String xmlStr, String tagName, String attrName) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(false); // never forget this!
    Document doc = null;
    DocumentBuilder builder = null;
    String value = null;/*from w w w.ja v  a2 s  . c o m*/

    try {
        builder = domFactory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        // Get the root element
        Node rootNode = doc.getFirstChild();
        NodeList nodeList = doc.getElementsByTagName(tagName);
        if ((nodeList.getLength() == 0) || (nodeList.item(0).getAttributes().getNamedItem(attrName) == null)) {
            logger.error("Either node " + tagName + " or attribute " + attrName + " not found.");
        } else {
            value = nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue();
            logger.debug("value of " + tagName + " attribute: " + attrName + " = " + value);
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

    return value;
}

From source file:edu.emory.library.tast.database.tabscommon.VisibleAttribute.java

private static void loadConfig() {
    try {/*www .  j av  a 2  s. c o m*/
        Document document = new XMLConfiguration("table-attributes.xml").getDocument();
        Node mainNode = document.getFirstChild();
        if (mainNode != null) {
            if (mainNode.getNodeType() == Node.ELEMENT_NODE) {
                NodeList attrs = mainNode.getChildNodes();
                for (int j = 0; j < attrs.getLength(); j++) {
                    if (attrs.item(j).getNodeType() == Node.ELEMENT_NODE) {
                        VisibleAttribute attr = VisibleAttribute.fromXML(attrs.item(j));
                        visibleAttributes.put(attr.getName(), attr);
                    }
                }
            }
        }
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Convert the given Document to an XML String.
 * <p>/*  ww w  .j av a2s  .c  o m*/
 * This method is a simplified version of...
 * <p>
 * <code>
 *    ByteArrayOutputStream out = new ByteArrayOutputStream();
 *    javax.xml.Transformer transformer = TransformerFactory.newInstance().newTransformer();
 *    transformer.transform( new DOMSource( node ), new StreamResult( out ));
 *    return out.toString();
 * </code>
 * <p>
 * ...but not all platforms (eg. Android) support <code>javax.xml.transform.Transformer</code>.
 */

public static String documentToString(Document document, boolean pretty) {

    // Nothing to do?

    if (document == null) {
        return "";
    }

    return nodeToString(document.getFirstChild(), pretty);
}

From source file:Main.java

public static String setAttribute(String xmlStr, String tagName, String attrName, String newValue) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(false); // never forget this!
    int i, j;//from   w ww .  j  a  v a2s .c  o  m
    Document doc = null;
    DocumentBuilder builder = null;

    StringWriter stringOut = new StringWriter();
    try {
        builder = domFactory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        // Get the root element
        Node rootNode = doc.getFirstChild();
        NodeList nodeList = doc.getElementsByTagName(tagName);
        if ((nodeList.getLength() == 0) || (nodeList.item(0).getAttributes().getNamedItem(attrName) == null)) {
            logger.error("Either node " + tagName + " or attribute " + attrName + " not found.");
        } else {
            logger.debug("value of " + tagName + " attribute: " + attrName + " = "
                    + nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue());
            nodeList.item(0).getAttributes().getNamedItem(attrName).setNodeValue(newValue);

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(stringOut);
            // StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);
            logger.debug("Updated XML: \n" + stringOut.toString());
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

    return stringOut.toString();
}

From source file:Main.java

/**
 * Adds a new node to a file./* ww  w .j  a  v  a2s  .co m*/
 *
 * @param nodeType {@link String} The type of the element to add.
 * @param idField {@link String} The name of the field used to identify this
 * node.
 * @param nodeID {@link String} The identifier for this node, so its data
 * can be later retrieved and modified.
 * @param destFile {@link File} The file where the node must be added.
 * @param attributes {@link ArrayList} of array of String. The arrays must
 * be bidimensional (first index must contain attribute name, second one
 * attribute value). Otherwise, an error will be thrown. However, if
 * <value>null</value>, it is ignored.
 */
public static void addNode(String nodeType, String idField, String nodeID, File destFile,
        ArrayList<String[]> attributes) {
    if (attributes != null) {
        for (Iterator<String[]> it = attributes.iterator(); it.hasNext();) {
            if (it.next().length != 2) {
                throw new IllegalArgumentException("Invalid attribute combination");
            }
        }
    }
    /*
     * XML DATA CREATION - BEGINNING
     */
    DocumentBuilder docBuilder;
    Document doc;
    try {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = docBuilder.parse(destFile);
    } catch (SAXException | IOException | ParserConfigurationException ex) {
        return;
    }

    Node index = doc.getFirstChild(), newElement = doc.createElement(nodeType);
    NamedNodeMap elementAttributes = newElement.getAttributes();

    Attr attrID = doc.createAttribute(idField);
    attrID.setValue(nodeID);
    elementAttributes.setNamedItem(attrID);

    if (attributes != null) {
        for (Iterator<String[]> it = attributes.iterator(); it.hasNext();) {
            String[] x = it.next();
            Attr currAttr = doc.createAttribute(x[0]);
            currAttr.setValue(x[1]);
            elementAttributes.setNamedItem(currAttr);
        }
    }

    index.appendChild(newElement);
    /*
     * XML DATA CREATION - END
     */

    /*
     * XML DATA DUMP - BEGINNING
     */
    Transformer transformer;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException ex) {
        return;
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    try {
        transformer.transform(source, result);
    } catch (TransformerException ex) {
        return;
    }

    String xmlString = result.getWriter().toString();
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(destFile))) {
        bufferedWriter.write(xmlString);
    } catch (IOException ex) {
    }
    /*
     * XML DATA DUMP - END
     */
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private static Rule wrap(InsertElementRule r) {
    return new Rule(r.xpath(), r.id()) {
        @Override/*from w ww  .jav a  2  s .com*/
        public void apply(Document document, Node matchedNode) throws Exception {
            final Document newDocument = parseXMLFragment(r.insert());
            final Node firstChild = newDocument.getFirstChild();
            final Node adoptedNode = document.importNode(firstChild, true);
            matchedNode.appendChild(adoptedNode);
        }

        @Override
        public String toString() {
            return "INSERT ELEMENT: " + r.xpath() + " with '" + r.insert();
        }
    };
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private static Rule wrap(ReplaceRule r) {
    final String newValue;

    if (!ContextRewritingBootStrapper.NULL_STRING.equals(r.replacement())) {
        if (r.replacementClassName() != ReplaceRule.NULL_CLASS) {
            throw new RuntimeException("Either replacement or replacementClassName needs to be set");
        }/*from  ww w .  j a  va 2 s . c  o  m*/
        newValue = r.replacement();
    } else if (r.replacementClassName() != ReplaceRule.NULL_CLASS) {
        newValue = r.replacementClassName().getName();
    } else {
        throw new RuntimeException(
                "You need to provide EITHER 'replacement' OR 'replacementClassName' attributes");
    }
    return new Rule(r.xpath(), r.id()) {
        public void apply(Document document, Node matchedNode) throws Exception {
            switch (matchedNode.getNodeType()) {
            case Node.ATTRIBUTE_NODE:
                matchedNode.setNodeValue(newValue);
                break;
            case Node.ELEMENT_NODE:
                final Document replDocument = parseXMLFragment(newValue);
                final Node firstChild = replDocument.getFirstChild();
                final Node adoptedNode = document.importNode(firstChild, true);
                matchedNode.getParentNode().replaceChild(adoptedNode, matchedNode);
                break;
            default:
                throw new RuntimeException();
            }
        }

        @Override
        public String toString() {
            return "REPLACE: " + r.xpath() + " with '" + newValue;
        }
    };
}

From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java

public static Chart createDefaultChart() {
    Log logger = LogFactory.getLog(ChartsPlugin.class);
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$
    Chart chart = new Chart();

    File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$
    if (file.exists() == true) {
        try {// www . ja  va 2s  .  c  o  m
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);

            NodeList firstNode = document.getFirstChild().getChildNodes();
            for (int r = 0; r < firstNode.getLength(); r++) {
                Node item = firstNode.item(r);
                Node valueNode = item.getFirstChild();
                String nodeName = item.getNodeName();

                if (valueNode != null) {
                    if (nodeName.equalsIgnoreCase("compression") == true) //$NON-NLS-1$
                        chart.setCompression(Integer.parseInt(valueNode.getNodeValue()));
                    else if (nodeName.equalsIgnoreCase("period") == true) //$NON-NLS-1$
                        chart.setPeriod(Integer.parseInt(valueNode.getNodeValue()));
                    else if (nodeName.equalsIgnoreCase("autoScale") == true) //$NON-NLS-1$
                        chart.setAutoScale(new Boolean(valueNode.getNodeValue()).booleanValue());
                    else if (nodeName.equalsIgnoreCase("begin") == true) //$NON-NLS-1$
                    {
                        try {
                            chart.setBeginDate(dateTimeFormat.parse(valueNode.getNodeValue()));
                        } catch (Exception e) {
                            logger.warn(e.toString());
                        }
                    } else if (nodeName.equalsIgnoreCase("end") == true) //$NON-NLS-1$
                    {
                        try {
                            chart.setEndDate(dateTimeFormat.parse(valueNode.getNodeValue()));
                        } catch (Exception e) {
                            logger.warn(e.toString());
                        }
                    }
                }
                if (nodeName.equalsIgnoreCase("row")) //$NON-NLS-1$
                {
                    ChartRow row = new ChartRow(new Integer(r));
                    row.setParent(chart);

                    NodeList tabList = item.getChildNodes();
                    for (int t = 0; t < tabList.getLength(); t++) {
                        item = tabList.item(t);
                        nodeName = item.getNodeName();
                        if (nodeName.equalsIgnoreCase("tab")) //$NON-NLS-1$
                        {
                            ChartTab tab = new ChartTab(new Integer(t));
                            tab.setParent(row);
                            tab.setLabel(((Node) item).getAttributes().getNamedItem("label").getNodeValue()); //$NON-NLS-1$

                            NodeList indicatorList = item.getChildNodes();
                            for (int i = 0; i < indicatorList.getLength(); i++) {
                                item = indicatorList.item(i);
                                nodeName = item.getNodeName();
                                if (nodeName.equalsIgnoreCase("indicator")) //$NON-NLS-1$
                                {
                                    ChartIndicator indicator = new ChartIndicator(new Integer(i));
                                    indicator.setParent(tab);
                                    indicator.setPluginId(((Node) item).getAttributes().getNamedItem("pluginId") //$NON-NLS-1$
                                            .getNodeValue());

                                    NodeList parametersList = item.getChildNodes();
                                    for (int p = 0; p < parametersList.getLength(); p++) {
                                        item = parametersList.item(p);
                                        nodeName = item.getNodeName();
                                        if (nodeName.equalsIgnoreCase("param")) //$NON-NLS-1$
                                        {
                                            String key = ((Node) item).getAttributes().getNamedItem("key") //$NON-NLS-1$
                                                    .getNodeValue();
                                            String value = ((Node) item).getAttributes().getNamedItem("value") //$NON-NLS-1$
                                                    .getNodeValue();
                                            indicator.getParameters().put(key, value);
                                        }
                                    }

                                    tab.getIndicators().add(indicator);
                                } else if (nodeName.equalsIgnoreCase("object")) //$NON-NLS-1$
                                {
                                    ChartObject object = new ChartObject(new Integer(i));
                                    object.setParent(tab);
                                    object.setPluginId(((Node) item).getAttributes().getNamedItem("pluginId") //$NON-NLS-1$
                                            .getNodeValue());

                                    NodeList parametersList = item.getChildNodes();
                                    for (int p = 0; p < parametersList.getLength(); p++) {
                                        item = parametersList.item(p);
                                        nodeName = item.getNodeName();
                                        if (nodeName.equalsIgnoreCase("param")) //$NON-NLS-1$
                                        {
                                            String key = ((Node) item).getAttributes().getNamedItem("key") //$NON-NLS-1$
                                                    .getNodeValue();
                                            String value = ((Node) item).getAttributes().getNamedItem("value") //$NON-NLS-1$
                                                    .getNodeValue();
                                            object.getParameters().put(key, value);
                                        }
                                    }

                                    tab.getObjects().add(object);
                                }
                            }

                            row.getTabs().add(tab);
                        }
                    }

                    chart.getRows().add(row);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    chart.clearChanged();

    return chart;
}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

private static final SOAPMessage toMessage(Document jdomDocument) throws IOException, SOAPException {
    SOAPMessage message = MessageFactory.newInstance().createMessage();
    SOAPPart sp = message.getSOAPPart();
    sp.setContent(new DOMSource(jdomDocument.getFirstChild()));

    return message;
}

From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java

private static final SOAPMessage toMessage(final Document jdomDocument) throws IOException, SOAPException {
    final SOAPMessage message = MessageFactory.newInstance().createMessage();
    final SOAPPart sp = message.getSOAPPart();
    sp.setContent(new DOMSource(jdomDocument.getFirstChild()));

    return message;
}