Example usage for org.w3c.dom Document appendChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Document 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:com.marklogic.client.test.DeleteSearchTest.java

public static void writeDoc() throws Exception {
    Document domDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = domDocument.createElement("root");
    root.setAttribute("xml:lang", "en");
    root.setAttribute("foo", "bar");
    root.appendChild(domDocument.createElement("child"));
    root.appendChild(domDocument.createTextNode("mixed"));
    domDocument.appendChild(root);

    @SuppressWarnings("unused")
    String domString = ((DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .getDOMImplementation()).createLSSerializer().writeToString(domDocument);

    XMLDocumentManager docMgr = Common.client.newXMLDocumentManager();
    docMgr.write(docId, new DOMHandle().with(domDocument));
}

From source file:Main.java

private static String getValueExceptTags(String xmlContent, String... tags)
        throws TransformerException, SAXException, IOException, ParserConfigurationException {

    Document document = parse(xmlContent, CHARSET_UTF8);
    Element rootElement = document.getDocumentElement();
    replace2TextExceptTags(document, rootElement, tags);

    String rootTag = "xml_root_tag";
    Document newDocument = generate();
    Element newRootElement = newDocument.createElement(rootTag);
    newDocument.appendChild(newRootElement);
    copyNode(newDocument, newRootElement, rootElement);

    String text = write(newDocument);
    int startIndex = text.indexOf(">", text.indexOf("<" + rootTag));
    int lastIndex = text.lastIndexOf("</" + rootTag + ">");

    String result = "";
    if (startIndex > 0 && lastIndex > 0) {
        result = text.substring(startIndex + 1, lastIndex);
    }/*from  w  ww  .jav  a2  s.co  m*/

    return result;
}

From source file:net.padaf.xmpbox.SaveMetadataHelper.java

/**
 * Prepare XMP Saving Put data necessary to make a well-formed XMP
 * /*from   w ww .  j  a v a 2s  .c  o m*/
 * @param metadata
 *            metadata concerned by the serialization processing
 * @param intoXPacket
 *            true if Processing instruction must be embedded
 * @return The DOM Document which will represent the serialized metadata
 */
protected static Document prepareSaving(XMPMetadata metadata, boolean intoXPacket) {
    Document newdoc = (Document) metadata.getFuturOwner().cloneNode(true);
    if (intoXPacket) {
        ProcessingInstruction beginXPacket = newdoc.createProcessingInstruction("xpacket",
                "begin=\"" + metadata.getXpacketBegin() + "\" id=\"" + metadata.getXpacketId() + "\"");
        newdoc.appendChild(beginXPacket);
    }

    Element xmpMeta = newdoc.createElementNS("adobe:ns:meta/", "x:xmpmeta");
    xmpMeta.setAttributeNS(XMPSchema.NS_NAMESPACE, "xmlns:x", "adobe:ns:meta/");

    newdoc.appendChild(xmpMeta);
    Element elem = (Element) metadata.getContainerElement().cloneNode(true);
    newdoc.adoptNode(elem);
    xmpMeta.appendChild(elem);

    if (intoXPacket) {
        ProcessingInstruction endXPacket = newdoc.createProcessingInstruction("xpacket",
                metadata.getEndXPacket());
        newdoc.appendChild(endXPacket);
    }
    return newdoc;
}

From source file:de.ingrid.interfaces.csw.domain.encoding.impl.XMLEncoding.java

protected static Document extractFromDocument(Node node) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//w  ww.  j  av  a 2 s .  com
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Node copy = node.cloneNode(true);
    Node adopted = doc.adoptNode(copy);
    doc.appendChild(adopted);
    return doc;
}

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);

    Element uri = doc.createElement("uri");
    uri.setTextContent(parentPost.mId);//from   www  . ja  v  a 2s. c  o m
    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:it.unitn.disi.smatch.webapi.model.JSONHelper.java

public static Document wrapJsonToXml(JSONObject obj) throws ParserConfigurationException {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = doc.createElement(TAG_WEBAPI);
    Element el = doc.createElement(TAG_JSON_DATA);
    Text txt = doc.createTextNode(obj.toString());
    el.appendChild(txt);// ww  w . j  a v  a 2  s.c o m
    root.appendChild(el);
    doc.appendChild(root);
    return doc;
}

From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java

/**
 * Extracts sentence nodes from a POS-tagger XML document.  These sentences are intended to provide some notion of
 * locality for identified chemical entities.
 *
 * @param docBuilder A document builder to use when producing single-sentence XML documents.
 * @param doc        The POS-tagger XML document from which to extract sentences.
 * @return A list of single-sentence documents.
 * @throws ParserConfigurationException/*w ww  .  java  2s  .  co  m*/
 * @throws XPathExpressionException
 */
private static List<Document> findSentences(DocumentBuilder docBuilder, Document doc)
        throws ParserConfigurationException, XPathExpressionException {
    if (doc != null) {
        // TODO: is there a more efficient yet still safe way to do this?
        XPath xpath = Util.getXPathFactory().newXPath();
        // TODO: get rid of this inline xpath compilation, run during setup.
        NodeList nodes = (NodeList) xpath.evaluate(SENTENCE_PATH, doc, XPathConstants.NODESET);

        List<Document> docList = new ArrayList<>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);

            /* With help from:
             * http://examples.javacodegeeks.com/core-java/xml/dom/copy-nodes-subtree-from-one-dom-document-to-another/ */
            org.w3c.dom.Document newDoc = docBuilder.newDocument();
            Element rootElement = newDoc.createElement(SENTENCE_DOC_HEADER);
            Node newNode = newDoc.importNode(n, true);
            rootElement.appendChild(newNode);
            newDoc.appendChild(rootElement);
            docList.add(newDoc);
        }
        return docList;
    } else {
        // TODO: log here.
        return new ArrayList<>(0);
    }
}

From source file:net.sf.jasperreports.engine.util.JRXmlUtils.java

/**
 * Creates a document having a node as root.
 * /*from   w  w  w. j a v a  2 s . c  o m*/
 * @param sourceNode the node
 * @return a document having the specified node as root
 * @throws JRException
 */
public static Document createDocument(Node sourceNode, boolean isNamespaceAware) throws JRException {
    Document doc = JRXmlUtils.createDocumentBuilder(isNamespaceAware).newDocument();
    Node source;
    if (sourceNode.getNodeType() == Node.DOCUMENT_NODE) {
        source = ((Document) sourceNode).getDocumentElement();
    } else {
        source = sourceNode;
    }

    Node node = doc.importNode(source, true);
    doc.appendChild(node);

    return doc;
}

From source file:de.betterform.xml.xforms.model.constraints.RelevanceSelector.java

private static void addElement(Document relevantDocument, Node instanceNode) {
    Element relevantElement;// w w w. j  a  v  a 2s  .c  om

    if (instanceNode.getNamespaceURI() == null) {
        relevantElement = relevantDocument.createElement(instanceNode.getNodeName());
    } else {
        relevantElement = relevantDocument.createElementNS(instanceNode.getNamespaceURI(),
                instanceNode.getNodeName());
    }

    relevantDocument.appendChild(relevantElement);
    addAttributes(relevantElement, instanceNode);
    addChildren(relevantElement, instanceNode);
}

From source file:com.hpe.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java

private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException {
    /*<Mtbx>/*from   w  ww.  jav a  2s  .co m*/
    <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1">
     <Parameter name="A" value="abc" type="string"/>
     <DataTable path="${WORKSPACE}\aa\bbb.xslx"/>
      .
     </Test>
     <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2">
    <Parameter name="p1" value="123" type="int"/>
    <Parameter name="p4" value="123.4" type="float"/>
     .
     </Test>
    </Mtbx>*/

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Mtbx");
        doc.appendChild(rootElement);

        for (TestExecutionInfo test : tests) {
            Element testElement = doc.createElement("Test");
            String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName())
                    ? test.getPackageName() + "\\"
                    : "") + test.getTestName();
            testElement.setAttribute("name", packageAndTestName);
            String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                    + (StringUtils.isEmpty(test.getPackageName()) ? ""
                            : OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getPackageName())
                    + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getTestName();
            testElement.setAttribute("path", path);

            if (StringUtils.isNotEmpty(test.getDataTable())) {
                Element dataTableElement = doc.createElement("DataTable");
                dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                        + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getDataTable());
                testElement.appendChild(dataTableElement);
            }

            rootElement.appendChild(testElement);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));

        return writer.toString();
    } catch (Exception e) {
        throw new IOException("Failed to build MTBX content : " + e.getMessage());
    }

}