Example usage for org.w3c.dom Document createTextNode

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

Introduction

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

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:com.crawljax.plugins.adi.Report.java

/**
 * Taken from ErrorReport.//from  w  w w . j a  v  a2s.  c o  m
 */
private Document addMarker(String id, Document doc, String xpath) {
    try {

        String prefixMarker = "###BEGINMARKER" + id + "###";
        String suffixMarker = "###ENDMARKER###";

        NodeList nodeList = XPathHelper.evaluateXpathExpression(doc, xpath);

        if (nodeList.getLength() == 0 || nodeList.item(0) == null) {
            return doc;
        }

        Node element = nodeList.item(0);

        if (element.getNodeType() == Node.ELEMENT_NODE) {
            Node beginNode = doc.createTextNode(prefixMarker);
            Node endNode = doc.createTextNode(suffixMarker);

            element.getParentNode().insertBefore(beginNode, element);
            if (element.getNextSibling() == null) {
                element.getParentNode().appendChild(endNode);
            } else {
                element.getParentNode().insertBefore(endNode, element.getNextSibling());
            }
        } else if (element.getNodeType() == Node.TEXT_NODE && element.getTextContent() != null) {
            element.setTextContent(prefixMarker + element.getTextContent() + suffixMarker);
        } else if (element.getNodeType() == Node.ATTRIBUTE_NODE) {
            element.setNodeValue(prefixMarker + element.getTextContent() + suffixMarker);
        }

        return doc;
    } catch (Exception e) {
        return doc;
    }
}

From source file:eu.europa.ec.markt.dss.applet.view.validationpolicy.EditView.java

private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath,
        final XmlDomAdapterNode clickedItem, final JTree tree) {
    final Element clickedElement = (Element) clickedItem.node;
    // popup menu for list -> add
    final JPopupMenu popup = new JPopupMenu();
    //delete node
    final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE"));
    menuItemToDelete.addActionListener(new ActionListener() {
        @Override/*  w  w  w. j  av  a  2 s . c  o  m*/
        public void actionPerformed(ActionEvent actionEvent) {
            // find the order# of the child to delete
            final int index = clickedItem.getParent().index(clickedItem);

            Node oldChild = clickedElement.getParentNode().removeChild(clickedElement);
            if (index > -1) {
                validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild);
            }
        }
    });
    popup.add(menuItemToDelete);

    //Add node/value
    final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree();
    final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree);
    for (final XsdNode xsdChild : children) {
        final String xmlName = xsdChild.getLastNameOfPath();

        final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " "
                + xsdChild.getType().toString().toLowerCase() + ")");
        popup.add(menuItem);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Document document = getModel().getValidationPolicy().getDocument();

                final Node newElement;
                if (xsdChild.getType() == XsdNodeType.TEXT) {
                    // TEXT element always appended (last child)
                    newElement = clickedElement.appendChild(document.createTextNode("VALUE"));
                } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) {
                    newElement = document.createAttributeNS(null, xmlName);
                    ((Attr) newElement).setValue("VALUE");
                    clickedElement.setAttributeNode((Attr) newElement);
                } else if (xsdChild.getType() == XsdNodeType.ELEMENT) {
                    final Element childToAdd = document
                            .createElementNS("http://dss.markt.ec.europa.eu/validation/diagnostic", xmlName);
                    // find the correct possition to add the child
                    // Get all allowed children
                    Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree);
                    boolean toAddSeen = false;
                    Element elementIsToAddBeforeThisOne = null;
                    for (final XsdNode allowed : childrenMap.keySet()) {
                        if (!toAddSeen && allowed == xsdChild) {
                            toAddSeen = true;
                            continue;
                        }
                        if (toAddSeen) {
                            final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS(
                                    "http://dss.markt.ec.europa.eu/validation/diagnostic",
                                    allowed.getLastNameOfPath());
                            if (elementsByTagNameNS.getLength() > 0) {
                                // we found an element that is supposed to be after the one to add
                                elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0);
                                break;
                            }
                        }
                    }

                    if (elementIsToAddBeforeThisOne != null) {
                        newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne);
                    } else {
                        newElement = clickedElement.appendChild(childToAdd);
                    }
                } else {
                    throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType());
                }

                document.normalizeDocument();

                int indexOfAddedItem = 0;
                final int childCount = clickedItem.childCount();
                for (int i = 0; i < childCount; i++) {
                    if (clickedItem.child(i).node == newElement) {
                        indexOfAddedItem = i;
                        break;
                    }
                }

                TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath,
                        new int[] { indexOfAddedItem }, new Object[] { newElement });
                validationPolicyTreeModel.fireTreeNodesInserted(event);
                tree.expandPath(selectedPath);

                //Update model
                getModel().getValidationPolicy().setXmlDom(new XmlDom(document));
            }
        });

    }
    popup.show(tree, mouseEvent.getX(), mouseEvent.getY());
}

From source file:uk.co.markfrimston.tasktree.TaskTree.java

protected Document saveToDocument() throws Exception {
    DocumentBuilder builder = builderFact.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element taskList = doc.createElement("tasklist");
    doc.appendChild(taskList);/*  w  ww.j  a  va 2s  .c  om*/
    taskList.appendChild(doc.createTextNode("\n\t"));
    Element tasks = doc.createElement("tasks");
    taskList.appendChild(tasks);
    taskList.appendChild(doc.createTextNode("\n"));
    addChildElementsFromTasks(doc, tasks, root, 1);

    return doc;
}

From source file:jp.co.opentone.bsol.framework.core.generator.excel.strategy.XmlWorkbookGeneratorStrategy.java

/**
 * ?????./*from  w ww.  ja v  a  2s . c  o m*/
 * @param doc DOM Document
 * @param value ?
 * @return 
 */
private Element createCell(Document doc, Object value) {
    Element cell = doc.createElement("Cell");
    setAttribute(cell, "ss:StyleID", isDate(value) ? ID_STYLE_DATE : ID_STYLE_NORMAL);

    Element v = doc.createElement("Data");
    setAttribute(v, "ss:Type", detectDataType(value));
    Node text = doc.createTextNode(formatValue(value));
    v.appendChild(text);

    cell.appendChild(v);

    return cell;
}

From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java

private void addDefaultIntellectualRights(Document doc) throws TransformerException {
    NodeList contacts = getContacts(doc);
    Element intellectualRightsElement = doc.createElement("intellectualRights");
    Element paraElement = doc.createElement("para");
    paraElement.appendChild(doc.createTextNode(INTELLECTUAL_RIGHTS_TEXT));
    intellectualRightsElement.appendChild(paraElement);
    Node datasetNode = getDatasetNode(doc);

    /* /*from  w  ww.ja v a  2 s  .c om*/
     * Determine where to insert the intellectualRights element. This
     * depends on the presence of nearby optional elements.
     */
    String insertBefore = null;
    if (hasElement(doc, DISTRIBUTION_PATH)) {
        insertBefore = DISTRIBUTION_PATH;
    } else if (hasElement(doc, COVERAGE_PATH)) {
        insertBefore = COVERAGE_PATH;
    } else if (hasElement(doc, PURPOSE_PATH)) {
        insertBefore = PURPOSE_PATH;
    } else if (hasElement(doc, MAINTENANCE_PATH)) {
        insertBefore = MAINTENANCE_PATH;
    } else {
        insertBefore = CONTACT_PATH;
    }

    NodeList insertNodeList = getElementNodeList(doc, insertBefore);
    Node insertNode = insertNodeList.item(0);
    datasetNode.insertBefore(intellectualRightsElement, insertNode);
}

From source file:eu.europa.esig.dss.applet.view.validationpolicy.EditView.java

private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath,
        final XmlDomAdapterNode clickedItem, final JTree tree) {
    final Element clickedElement = (Element) clickedItem.node;
    // popup menu for list -> add
    final JPopupMenu popup = new JPopupMenu();
    //delete node
    final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE"));
    menuItemToDelete.addActionListener(new ActionListener() {
        @Override//from ww w  . j a va 2  s  .c o m
        public void actionPerformed(ActionEvent actionEvent) {
            // find the order# of the child to delete
            final int index = clickedItem.getParent().index(clickedItem);

            Node oldChild = clickedElement.getParentNode().removeChild(clickedElement);
            if (index > -1) {
                validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild);
            }
        }
    });
    popup.add(menuItemToDelete);

    //Add node/value
    final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree();
    final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree);
    for (final XsdNode xsdChild : children) {
        final String xmlName = xsdChild.getLastNameOfPath();

        final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " "
                + xsdChild.getType().toString().toLowerCase() + ")");
        popup.add(menuItem);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Document document = getModel().getValidationPolicy().getDocument();

                final Node newElement;
                if (xsdChild.getType() == XsdNodeType.TEXT) {
                    // TEXT element always appended (last child)
                    newElement = clickedElement.appendChild(document.createTextNode("VALUE"));
                } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) {
                    newElement = document.createAttributeNS(null, xmlName);
                    ((Attr) newElement).setValue("VALUE");
                    clickedElement.setAttributeNode((Attr) newElement);
                } else if (xsdChild.getType() == XsdNodeType.ELEMENT) {
                    final Element childToAdd = document
                            .createElementNS("http://dss.esig.europa.eu/validation/diagnostic", xmlName);
                    // find the correct possition to add the child
                    // Get all allowed children
                    Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree);
                    boolean toAddSeen = false;
                    Element elementIsToAddBeforeThisOne = null;
                    for (final XsdNode allowed : childrenMap.keySet()) {
                        if (!toAddSeen && (allowed == xsdChild)) {
                            toAddSeen = true;
                            continue;
                        }
                        if (toAddSeen) {
                            final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS(
                                    "http://dss.esig.europa.eu/validation/diagnostic",
                                    allowed.getLastNameOfPath());
                            if (elementsByTagNameNS.getLength() > 0) {
                                // we found an element that is supposed to be after the one to add
                                elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0);
                                break;
                            }
                        }
                    }

                    if (elementIsToAddBeforeThisOne != null) {
                        newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne);
                    } else {
                        newElement = clickedElement.appendChild(childToAdd);
                    }
                } else {
                    throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType());
                }

                document.normalizeDocument();

                int indexOfAddedItem = 0;
                final int childCount = clickedItem.childCount();
                for (int i = 0; i < childCount; i++) {
                    if (clickedItem.child(i).node == newElement) {
                        indexOfAddedItem = i;
                        break;
                    }
                }

                TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath,
                        new int[] { indexOfAddedItem }, new Object[] { newElement });
                validationPolicyTreeModel.fireTreeNodesInserted(event);
                tree.expandPath(selectedPath);

                //Update model
                getModel().getValidationPolicy().setXmlDom(new XmlDom(document));
            }
        });

    }
    popup.show(tree, mouseEvent.getX(), mouseEvent.getY());
}

From source file:gov.medicaid.services.impl.FileNetServiceBean.java

/**
 * Creates the XML./*from w  w  w .  j  a  v a  2 s.  co  m*/
 * 
 * @param outFile
 *            the output file handler
 * @param attributes
 *            the content
 * @throws PortalServiceException
 *             if any error occurs
 */
private void createXML(File outFile, Map<String, String> attributes) throws PortalServiceException {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Document");
        doc.appendChild(rootElement);
        for (String key : attributes.keySet()) {
            Element indexVal = doc.createElement("Indexvalue");
            Attr attr = doc.createAttribute("name");
            attr.setValue(key);
            indexVal.setAttributeNode(attr);
            if (attributes.get(key) != null) {
                indexVal.appendChild(doc.createTextNode(attributes.get(key)));
            }
            rootElement.appendChild(indexVal);
        }
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(outFile);

        transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    } catch (TransformerException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    }

}

From source file:org.joy.config.Configuration.java

public void save() {
    try {/*from   w ww.j  a v  a 2s  .  c om*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element root = doc.createElement("configuration");
        doc.appendChild(root);

        Element classpathEle = doc.createElement("classpath");
        root.appendChild(classpathEle);
        for (String s : classPathEntries) {
            Element e = doc.createElement("entry");
            e.appendChild(doc.createTextNode(s));
            classpathEle.appendChild(e);
        }

        Element connectionsEle = doc.createElement("connections");
        root.appendChild(connectionsEle);
        for (DatabaseElement d : connectionHistory) {
            writeDatabase(connectionsEle, d);
        }

        Element e = doc.createElement("tagertProject");
        e.appendChild(doc.createTextNode(tagertProject));
        root.appendChild(e);

        e = doc.createElement("basePackage");
        e.appendChild(doc.createTextNode(basePackage));
        root.appendChild(e);

        e = doc.createElement("moduleName");
        e.appendChild(doc.createTextNode(moduleName));
        root.appendChild(e);

        Element templatesEle = doc.createElement("templates");
        root.appendChild(templatesEle);
        for (TemplateElement t : templates) {
            writeTemplate(templatesEle, t);
        }

        // Write the file
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(new File(configurationFile));
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.transform(ds, sr);
    } catch (Exception e) {
        LOGGER.info(e.getMessage(), e);
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

/**
 * Create a DOM element, containing the specified text.
 *
 * @param doc  Document// w  w  w . jav  a  2  s .c o  m
 * @param name The name of the element.
 * @param text The text.
 * @return Element
 */
public static Element createElement(Document doc, String name, String text) {
    if (name == null) {
        throw new XMLToolException("Element name cannot be null!");
    } else if (name.trim().length() == 0) {
        throw new XMLToolException("Element name has to contain at least one character!");
    }

    Element elem = doc.createElement(name);
    if (text != null) {
        Text textNode = doc.createTextNode(text);
        elem.appendChild(textNode);
    }

    return elem;
}

From source file:de.ingrid.interfaces.csw.server.cswt.impl.GenericServerCSWT.java

private Document createSummaryResponse(CSWTransactionResult result) throws ParserConfigurationException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);//from w  w w  .j  a  v a2  s .c om
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    DOMImplementation domImpl = docBuilder.getDOMImplementation();
    Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "csw:TransactionResponse", null);

    // create summary
    Element summary = doc.createElementNS(RESPONSE_NAMESPACE, "csw:TransactionSummary");
    summary.setAttribute("requestId", result.getRequestId());
    doc.getDocumentElement().appendChild(summary);

    int inserts = result.getNumberOfInserts();
    summary.appendChild(doc.createElementNS(RESPONSE_NAMESPACE, "totalInserted"))
            .appendChild(doc.createTextNode(String.valueOf(inserts)));
    int updates = result.getNumberOfUpdates();
    summary.appendChild(doc.createElementNS(RESPONSE_NAMESPACE, "totalUpdated"))
            .appendChild(doc.createTextNode(String.valueOf(updates)));
    int deletes = result.getNumberOfDeletes();
    summary.appendChild(doc.createElementNS(RESPONSE_NAMESPACE, "totalDeleted"))
            .appendChild(doc.createTextNode(String.valueOf(deletes)));

    // add insert results
    //        if (inserts > 0) {
    //            Element insertResult = doc.createElementNS(RESPONSE_NAMESPACE, "csw:InsertResult");
    //            doc.getDocumentElement().appendChild(insertResult);
    //            for (ActionResult curResult : result.getInsertResults()) {
    //                List<CSWRecord> records = curResult.getRecords();
    //                if (records.size() > 0) {
    //                    Node recordNode = records.get(0).getDocument().getFirstChild();
    //                    Action action = curResult.getAction();
    //                    String handle = action.getHandle();
    //                    if (handle != null && recordNode instanceof Element) {
    //                        ((Element)recordNode).setAttribute("handle", handle);
    //                    }
    //                    doc.adoptNode(recordNode);
    //                    insertResult.appendChild(recordNode);
    //                }
    //            }
    //        }
    return doc;

}