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.msopentech.odatajclient.engine.data.json.GeospatialJSONHandler.java

private static Element deserializePoint(final Document document, final Iterator<JsonNode> itor) {
    final Element point = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POINT);

    final Element ppos = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POS);
    point.appendChild(ppos);//ww  w  . jav  a  2s .c o m
    if (itor.hasNext()) {
        ppos.appendChild(document.createTextNode(itor.next().asText() + " " + itor.next().asText()));
    }

    return point;
}

From source file:DOMEdit.java

private static void makeNamelist(Document doc) {
        String names = null;//w ww .ja  va 2 s  .c o m
        Element root = doc.getDocumentElement();
        NodeList nameElements = root.getElementsByTagName("name");
        for (int i = 0; i < nameElements.getLength(); i++) {
            Element name = (Element) nameElements.item(i);
            Text nametext = (Text) name.getFirstChild();
            if (names == null) {
                names = nametext.getData();
            } else {
                names += ", " + nametext.getData();
            }
        }
        Element namelist = doc.createElement("names");
        Text namelisttext = doc.createTextNode(names);
        namelist.appendChild(namelisttext);
        root.insertBefore(namelist, root.getFirstChild());
    }

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

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

    try {//  w  ww.  j a v a  2s .c o  m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        Element node = document.createElement("title"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(chart.getTitle()));
        root.appendChild(node);
        node = document.createElement("compression"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getCompression())));
        root.appendChild(node);
        node = document.createElement("period"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod())));
        root.appendChild(node);
        node = document.createElement("autoScale"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale())));
        root.appendChild(node);
        if (chart.getBeginDate() != null) {
            node = document.createElement("begin"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate())));
            root.appendChild(node);
        }
        if (chart.getEndDate() != null) {
            node = document.createElement("end"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate())));
            root.appendChild(node);
        }
        for (int r = 0; r < chart.getRows().size(); r++) {
            ChartRow row = (ChartRow) chart.getRows().get(r);
            row.setId(new Integer(r));

            Element rowNode = document.createElement("row"); //$NON-NLS-1$
            root.appendChild(rowNode);

            for (int t = 0; t < row.getTabs().size(); t++) {
                ChartTab tab = (ChartTab) row.getTabs().get(t);
                tab.setId(new Integer(t));

                Element tabNode = document.createElement("tab"); //$NON-NLS-1$
                tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$
                rowNode.appendChild(tabNode);

                for (int i = 0; i < tab.getIndicators().size(); i++) {
                    ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i);
                    indicator.setId(new Integer(i));

                    Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }

                for (int i = 0; i < tab.getObjects().size(); i++) {
                    ChartObject object = (ChartObject) tab.getObjects().get(i);
                    object.setId(new Integer(i));

                    Element indicatorNode = document.createElement("object"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }
            }
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();

    } catch (Exception e) {
        logger.error(e.toString(), e);
    }
}

From source file:com.ibm.rpe.web.service.docgen.impl.GenerateBaseTemplate.java

private static void createTemplateXmls(String inputFile, BaseTemplateInput data)
        throws ParserConfigurationException, SAXException, IOException {
    String directory = (new File(inputFile)).getParent() + File.separator;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;

    builder = factory.newDocumentBuilder();

    Document document = builder.parse(new File(inputFile));

    NodeList nlist = document.getElementsByTagName("element");
    if (nlist != null && nlist.getLength() > 0) {
        for (int i = 0; i < nlist.getLength(); i++) {
            Node node = nlist.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element ele = (Element) node;
                String attr = ele.getAttribute("id");

                if (attr.contentEquals(data.getElementId())) {
                    Node newNode = document.createTextNode(data.getReplacement());
                    node.getParentNode().insertBefore(newNode, node);
                    try {
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }/* www .j a  v a  2  s  .  co  m*/
                    Node removedNode = node.getParentNode().removeChild(node);
                    // System.out.println(nodeToString(removedNode));
                    String removed = nodeToString(removedNode);
                    removed = replace(removed, data.getReplaceMap());
                    if (data.isReplaceElementId()) {
                        removed = replaceElementId(removed);
                    }
                    document.normalize();
                    FileUtils.writeFile(directory + data.getOutputFile(), removed);
                    System.out.println("Removed : " + ((Element) removedNode).getAttribute("id"));

                    try {
                        // prettyPrint(document);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
        FileUtils.writeFile(inputFile, transformToString(document));
    }
}

From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java

/**
 * execute DML/*  w w  w .j a  va2  s.  c o m*/
 * 
 * @param userDB
 * @param strQuery
 * @param listParam
 * @param resultType
 * @throws Exception
 */
public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam,
        final String resultType) throws Exception {
    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    Object effectObject = runSQLOther(userDB, strQuery, listParam);

    String strReturn = "";
    if (resultType.equals(RESULT_TYPE.CSV.name())) {
        final StringWriter stWriter = new StringWriter();
        CSVWriter csvWriter = new CSVWriter(stWriter, ',');

        String[] arryString = new String[2];
        arryString[0] = "effectrow";
        arryString[1] = String.valueOf(effectObject);
        csvWriter.writeNext(arryString);

        strReturn = stWriter.toString();
    } else if (resultType.equals(RESULT_TYPE.JSON.name())) {
        final JsonArray jsonArry = new JsonArray();
        JsonObject jsonObj = new JsonObject();
        jsonObj.addProperty("effectrow", String.valueOf(effectObject));
        jsonArry.add(jsonObj);

        strReturn = JSONUtil.getPretty(jsonArry.toString());
    } else {//if(resultType.equals(RESULT_TYPE.XML.name())) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.newDocument();
        final Element results = doc.createElement("Results");
        doc.appendChild(results);

        Element row = doc.createElement("Row");
        results.appendChild(row);
        Element node = doc.createElement("effectrow");
        node.appendChild(doc.createTextNode(String.valueOf(effectObject)));
        row.appendChild(node);

        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", 4);

        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        final StringWriter stWriter = new StringWriter();
        StreamResult sr = new StreamResult(stWriter);
        transformer.transform(domSource, sr);

        strReturn = stWriter.toString();
    }

    return strReturn;
}

From source file:com.aurel.track.exchange.docx.exporter.CustomXML.java

/**
 * Creates a dom element//from  ww  w  .ja v a 2  s .  c o m
 * @param elementName
 * @param elementValue
 * @param dom
 * @return
 */
private static Element createDomElement(String elementName, String elementValue, Document dom) {
    Element element = null;
    try {
        try {
            element = dom.createElement(elementName);
        } catch (DOMException e) {
            LOGGER.warn("Creating an XML node with the element name " + elementName
                    + " failed with dom exception " + e);
        }
        if (element == null) {
            return null;
        }
        if (elementValue == null || "".equals(elementValue.trim())) {
            element.appendChild(dom.createTextNode(""));
        } else {
            try {
                element.appendChild(dom.createTextNode(Html2Text.stripNonValidXMLCharacters(elementValue)));
            } catch (DOMException e) {
                LOGGER.info("Creating the node for text element " + elementName + " and the value "
                        + elementValue + " failed with dom exception " + e);
                element.appendChild(dom.createTextNode(""));
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Creating an XML node with the element name " + elementName + " failed with " + e);
    }
    return element;
}

From source file:Main.java

public static void setElementTextValue(Element e, String text, boolean cdata) {
    Document root = e.getOwnerDocument();
    e.normalize();//from  ww  w. j  a va 2 s.com
    if (e.hasChildNodes()) {
        NodeList nl = e.getChildNodes();

        /* This suxx: NodeList Object is changed when removing children !!!
           I will store all nodes that should be deleted in a Vector and delete them afterwards */
        int length = nl.getLength();

        List<Node> v = new ArrayList<Node>(nl.getLength());
        for (int i = 0; i < length; i++)
            if (nl.item(i) instanceof CharacterData)
                v.add(nl.item(i));
        for (Node n : v)
            e.removeChild(n);
    }

    if (cdata) {
        e.appendChild(root.createCDATASection(text));
    } else {
        e.appendChild(root.createTextNode(text));
    }
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * Creates a SelectFields Soap Object given a List<String> fieldnames object
 * which sets the fields to be retrieved.
 * /*  ww w.  j av  a2  s .  co  m*/
 * @param fieldnames
 * @return
 */
public static SelectFields generatePopulatedSelectFields(List<String> fieldnames) {

    SelectFields selfields = new SelectFields();
    StringBuffer arrayType = new StringBuffer();
    arrayType.append("string[");
    arrayType.append(fieldnames.size());
    arrayType.append("]");
    CommonAttributes commonAttributes = new CommonAttributes();
    commonAttributes.setHref(arrayType.toString());
    selfields.setCommonAttributes(commonAttributes);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        for (String fieldname : fieldnames) {
            Element element = document.createElement("string");
            Array array = new Array();
            array.getAnyList();
            selfields.setArray(array);
            element.appendChild(document.createTextNode(fieldname));
        }

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    }

    return selfields;

}

From source file:com.ephesoft.dcma.util.XMLUtil.java

/**
 * To append Leaf Child.//  w  w w.j a va  2 s . c  o  m
 * 
 * @param doc Document
 * @param parent Node
 * @param childName String
 * @param childData String
 */
public static void appendLeafChild(Document doc, Node parent, String childName, String childData) {
    Element child = doc.createElement(childName);
    if (childData != null && childData.length() != 0) {
        Text text = doc.createTextNode(childData);

        child.appendChild(text);
    }
    parent.appendChild(child);
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * Creates a NameValueList Soap Element given a List<String> namevalues
 * object which sets the fields to be retrieved.
 * // www  .java2s  .  c o  m
 * @param fieldnames
 * @return
 */
public static NameValueList generatePopulatedNameValueList(List<NameValue> namevalues) {

    NameValueList namevalueList = new NameValueList();
    StringBuffer arrayType = new StringBuffer();
    arrayType.append("name_value[");
    arrayType.append(namevalues.size());
    arrayType.append("]");
    Array array = new Array();
    ArrayType arrTypeObj = new ArrayType();
    arrTypeObj.setArrayType(arrayType.toString());

    ArrayAttributes atts = new ArrayAttributes();
    atts.setArrayType(arrTypeObj);

    namevalueList.setArrayAttributes(atts);
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        for (NameValue namevalue : namevalues) {
            Element name_value = document.createElement("name_value");

            Element name = document.createElement("name");
            Element value = document.createElement("value");

            name.appendChild(document.createTextNode(namevalue.getName()));
            value.appendChild(document.createTextNode(namevalue.getValue()));
            name_value.appendChild(name);
            name_value.appendChild(value);

            array.getAnyList().add(name_value);
        }

        namevalueList.setArray(array);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    }

    return namevalueList;

}