Example usage for org.w3c.dom Element appendChild

List of usage examples for org.w3c.dom Element appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Element appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:apps.ParsedPost.java

private static String createYahooAnswersQuestion(ParsedPost parentPost, ParsedPost post)
        throws ParserConfigurationException, TransformerException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("document");

    doc.appendChild(rootElement);/*  w  w w .  j a v  a 2 s.  c om*/

    Element uri = doc.createElement("uri");
    uri.setTextContent(parentPost.mId);
    rootElement.appendChild(uri);

    Element subject = doc.createElement("subject");
    subject.setTextContent(parentPost.mTitle);
    rootElement.appendChild(subject);

    Element content = doc.createElement("content");
    content.setTextContent(parentPost.mBody);
    rootElement.appendChild(content);

    Element bestanswer = doc.createElement("bestanswer");
    bestanswer.setTextContent(post.mBody);
    rootElement.appendChild(bestanswer);

    Element answer_item = doc.createElement("answer_item");
    answer_item.setTextContent(post.mBody);
    Element nbestanswers = doc.createElement("nbestanswers");
    nbestanswers.appendChild(answer_item);
    rootElement.appendChild(nbestanswers);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);

    transformer.transform(source, result);
    return "<vespaadd>" + xhlp.removeHeader(sw.toString()).replace("&", "&amp;") + "</vespaadd>\n";
}

From source file:eu.scidipes.toolkits.palibrary.utils.XMLUtils.java

/**
 * Transforms a collection of {@link FormField} objects into a simple XML document
 * /*from w  ww.j a v  a2s. c om*/
 * @param fields
 *            a collection of form fields
 * @return an xml document representing the form fields, or null if the passed collection is null or empty, or all
 *         form fields have an empty value
 */
public static Node formFieldsToMetadata(final Collection<? extends FormField> fields) {
    if (fields != null && !fields.isEmpty()) {
        try {
            final Document xml;

            synchronized (documentBuilderFactory) {
                xml = documentBuilderFactory.newDocumentBuilder().newDocument();
            }

            xml.setXmlStandalone(true);
            final Element metaData = xml.createElement("metadata");
            int completedFieldCount = 0;

            for (final FormField field : fields) {
                if (!StringUtils.isEmpty(field.getValue())) {
                    completedFieldCount++;
                    final Element metaDataEntry = xml.createElement("metadataentry");
                    final Element entryName = xml.createElement("entryname");
                    final Element entryValue = xml.createElement("entryvalue");

                    entryName.setTextContent(field.getDisplayName());
                    entryValue.setTextContent(field.getValue());

                    metaDataEntry.appendChild(entryName);
                    metaDataEntry.appendChild(entryValue);
                    metaData.appendChild(metaDataEntry);
                }
            }

            if (completedFieldCount > 0) {
                xml.appendChild(metaData);
                return xml;
            } else {
                return null;
            }

        } catch (final ParserConfigurationException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    return null;
}

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 w w . ja  v a  2  s .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.viettel.ws.client.JDBCUtil.java

/**
 * Create document using DOM api/*from ww  w .  j a  v a2s.  co m*/
 *
 * @param rs a result set
 * @return A document of a result set
 * @throws ParserConfigurationException - If error when parse string
 * @throws SQLException - If error when read data from database
 */
public static Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(FEATURE_GENERAL_ENTITIES, false);
    factory.setFeature(FEATURE_PARAMETER_ENTITIES, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    return doc;
}

From source file:de.akra.idocit.wsdl.services.DocumentationGenerator.java

/**
 * Adds the <code>text</code> as {@link Node#TEXT_NODE}s to the <code>element</code>.
 * Newline and tabulator characters are replaced with &lt;br/&gt; and &lt;tab/&gt;
 * elements./*  www  .  j  a  v  a 2s.  c  om*/
 * 
 * @param element
 *            The {@link Element} to which the <code>text</code> should be added.
 * @param text
 *            The text to convert and add to the <code>element</code>.
 * @return The <code>element</code>.
 */
private static Element addTextAsNodes(Element element, String text) {
    String escapedText = StringEscapeUtils.escapeHtml4(text);

    StringBuilder tmpText = new StringBuilder();

    for (int i = 0; i < escapedText.length(); ++i) {
        switch (escapedText.charAt(i)) {
        case '\t':
            if (tmpText.length() > 0) {
                element.appendChild(domDocument.createTextNode(tmpText.toString()));
                tmpText = new StringBuilder();
            }
            element.appendChild(domDocument.createElement(XML_TAG_TAB));
            break;

        case '\r':
            if (tmpText.length() > 0) {
                element.appendChild(domDocument.createTextNode(tmpText.toString()));
                tmpText = new StringBuilder();
            }
            element.appendChild(domDocument.createElement(XML_TAG_BR));

            // if CR and LF are together, replace it only once
            // Changes due to Issue #2
            if ((escapedText.length() > i + 1) && escapedText.charAt(i + 1) == '\n')
            // End changes due to Issue #2
            {
                i++;
            }
            break;

        case '\n':
            if (tmpText.length() > 0) {
                element.appendChild(domDocument.createTextNode(tmpText.toString()));
                tmpText = new StringBuilder();
            }
            element.appendChild(domDocument.createElement(XML_TAG_BR));

            // if CR and LF are together, replace it only once
            // Changes due to Issue #2
            if ((escapedText.length() > i + 1) && escapedText.charAt(i + 1) == '\r')
            // End changes due to Issue #2
            {
                i++;
            }
            break;

        default:
            tmpText.append(escapedText.charAt(i));
            break;
        }
    }

    // append pending text
    if (tmpText.length() > 0) {
        element.appendChild(domDocument.createTextNode(tmpText.toString()));
    }

    return element;
}

From source file:Main.java

public static Element getContactTypeWithText(Document doc, String elementName, String name, String title,
        String street, String city, String state, String zip, String officePhone, String mobilePhone,
        String email) {/*from   w w  w  .j  av  a  2 s. com*/

    Element elem_contact_type = doc.createElement(elementName);

    Element elem_name = getElementWithText(doc, "Name", name);
    Element elem_title = getElementWithText(doc, "Title", title);
    Element elem_address = getAddressTypeWithText(doc, street, city, state, zip);
    Element elem_officePhone = getPhoneTypeWithText(doc, "OfficePhone", officePhone);
    Element elem_mobilePhone = getPhoneTypeWithText(doc, "MobilePhone", mobilePhone);
    Element elem_email = getElementWithText(doc, "Email", email);

    elem_contact_type.appendChild(elem_name);
    elem_contact_type.appendChild(elem_title);
    if (street != null) {
        elem_contact_type.appendChild(elem_address);
    }

    if (officePhone != null) {
        elem_contact_type.appendChild(elem_officePhone);
    }

    if (mobilePhone != null) {
        elem_contact_type.appendChild(elem_mobilePhone);
    }

    elem_contact_type.appendChild(elem_email);

    return elem_contact_type;
}

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 w  w  .j  a  v  a 2 s.  co 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.cmu.cs.lti.ark.fn.evaluation.PrepareFullAnnotationXML.java

/**
 * Given several parallel lists of predicted frame instances, including their frame elements, create an XML file 
 * for the full-text annotation predicted by the model.
 * @param predictedFELines Lines encoding predicted frames & FEs in the same format as the .sentences.frame.elements files
 * @param sentenceNums Global sentence number for the first sentence being predicted, so as to map FE lines to items in parses/orgLines
 * @param parses Lines encoding the parse for each sentence
 * @param origLines The original sentences, untokenized
 * @return//from www  . jav  a2 s . c o  m
 */
public static Document createXMLDoc(List<String> predictedFELines, Range sentenceNums, List<String> parses,
        List<String> origLines) {
    final Document doc = XmlUtils.getNewDocument();
    final Element corpus = doc.createElement("corpus");
    addAttribute(doc, "ID", corpus, "100");
    addAttribute(doc, "name", corpus, "ONE");
    addAttribute(doc, "XMLCreated", corpus, new Date().toString());
    final Element documents = doc.createElement("documents");
    corpus.appendChild(documents);

    final Element document = doc.createElement("document");
    addAttribute(doc, "ID", document, "1");
    addAttribute(doc, "description", document, "TWO");
    documents.appendChild(document);

    final Element paragraphs = doc.createElement("paragraphs");
    document.appendChild(paragraphs);

    final Element paragraph = doc.createElement("paragraph");
    addAttribute(doc, "ID", paragraph, "2");
    addAttribute(doc, "documentOrder", paragraph, "1");
    paragraphs.appendChild(paragraph);

    final Element sentences = doc.createElement("sentences");

    // Map sentence offsets to frame annotation data points within each sentence
    final TIntObjectHashMap<Set<String>> predictions = new TIntObjectHashMap<Set<String>>();
    for (String feLine : predictedFELines) {
        final int sentNum = DataPointWithFrameElements.parseFrameNameAndSentenceNum(feLine).second;

        if (!predictions.containsKey(sentNum))
            predictions.put(sentNum, new THashSet<String>());

        predictions.get(sentNum).add(feLine);
    }

    for (int sent = sentenceNums.start; sent < sentenceNums.start + sentenceNums.length(); sent++) {
        final String parseLine = parses.get(sent - sentenceNums.start);

        final Element sentence = doc.createElement("sentence");
        addAttribute(doc, "ID", sentence, "" + (sent - sentenceNums.start));

        final Element text = doc.createElement("text");
        final String origLine = origLines.get(sent - sentenceNums.start);
        final Node textNode = doc.createTextNode(origLine);
        text.appendChild(textNode);
        sentence.appendChild(text);
        final Element tokensElt = doc.createElement("tokens");
        final String[] tokens = origLine.trim().split(" ");
        for (int i : xrange(tokens.length)) {
            final String token = tokens[i];
            final Element tokenElt = doc.createElement("token");
            addAttribute(doc, "index", tokenElt, "" + i);
            final Node tokenNode = doc.createTextNode(token);
            tokenElt.appendChild(tokenNode);
            tokensElt.appendChild(tokenElt);
        }
        sentence.appendChild(tokensElt);

        final Element annotationSets = doc.createElement("annotationSets");

        int frameIndex = 0; // index of the predicted frame within the sentence
        final Set<String> feLines = predictions.get(sent);

        if (feLines != null) {
            final List<DataPointWithFrameElements> dataPoints = Lists.newArrayList();
            for (String feLine : feLines) {
                final DataPointWithFrameElements dp = new DataPointWithFrameElements(parseLine, feLine);
                dp.processOrgLine(origLine);
                dataPoints.add(dp);
            }
            final Set<String> seenTargetSpans = Sets.newHashSet();
            for (DataPointWithFrameElements dp : dataPoints) {
                final String targetIdxsString = Arrays.toString(dp.getTargetTokenIdxs());
                if (seenTargetSpans.contains(targetIdxsString)) {
                    System.err.println("Duplicate target tokens: " + targetIdxsString
                            + ". Skipping. Sentence id: " + sent);
                    continue; // same target tokens should never show up twice in the same sentence
                } else {
                    seenTargetSpans.add(targetIdxsString);
                }
                assert dp.rank == 1; // this doesn't work with k-best lists anymore
                final String frame = dp.getFrameName();
                // Create the <annotationSet> Element for the predicted frame annotation, and add it under the sentence
                Element annotationSet = buildAnnotationSet(frame, ImmutableList.of(dp), doc,
                        sent - sentenceNums.start, frameIndex);
                annotationSets.appendChild(annotationSet);
                frameIndex++;
            }
        }
        sentence.appendChild(annotationSets);
        sentences.appendChild(sentence);
    }
    paragraph.appendChild(sentences);
    doc.appendChild(corpus);
    return doc;
}

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

/**
 * execute DML//from w w  w.j a v  a2s  .  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: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.
 * //w w w . ja  v a 2s. 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;

}