Example usage for org.w3c.dom Document createElementNS

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

Introduction

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

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:com.verisign.epp.codec.verificationcode.EPPEncodedSignedCodeValue.java

/**
 * Sets all this instance's data in the given XML document
 * /*from www  . j ava  2s .c  o m*/
 * @param aDocument
 *            a DOM Document to attach data to.
 * @return The root element of this component.
 * @throws EPPEncodeException
 *             Thrown if any errors prevent encoding.
 */
public Element encode(Document aDocument) throws EPPEncodeException {
    cat.debug("EPPEncodedSignedCodeValue.encode(Document): enter");

    if (aDocument == null) {
        throw new EPPEncodeException("aDocument is null" + " on in EPPSignedCode.encode(Document)");
    }

    Element root = aDocument.createElementNS(EPPVerificationCodeExtFactory.NS,
            EPPVerificationCodeExtFactory.NS_PREFIX + ":" + ELM_LOCALNAME);

    byte[] signedCodeXml = super.encode();

    String base64EncodedText = new String(Base64.encodeBase64(signedCodeXml, true));

    Text currVal = aDocument.createTextNode(base64EncodedText);
    root.appendChild(currVal);
    cat.debug("EPPEncodedSignedCodeValue.encode(Document): exit - encoded");
    return root;
}

From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(String signatureZipEntryName, OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerFactoryConfigurationError, TransformerException {
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOfficeOpenXMLDocumentURL().openStream());
    ZipEntry zipEntry;//  ww w . j a  va  2  s.  com
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        LOG.debug("copy ZIP entry: " + zipEntry.getName());
        ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
        zipOutputStream.putNextEntry(newZipEntry);
        if ("[Content_Types].xml".equals(zipEntry.getName())) {
            Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            Element typesElement = contentTypesDocument.getDocumentElement();

            /*
             * We need to add an Override element.
             */
            Element overrideElement = contentTypesDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/content-types", "Override");
            overrideElement.setAttribute("PartName", "/" + signatureZipEntryName);
            overrideElement.setAttribute("ContentType",
                    "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml");
            typesElement.appendChild(overrideElement);

            Element nsElement = contentTypesDocument.createElement("ns");
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
                    "http://schemas.openxmlformats.org/package/2006/content-types");
            NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument,
                    "/tns:Types/tns:Default[@Extension='sigs']", nsElement);
            if (0 == nodeList.getLength()) {
                /*
                 * Add Default element for 'sigs' extension.
                 */
                Element defaultElement = contentTypesDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/content-types", "Default");
                defaultElement.setAttribute("Extension", "sigs");
                defaultElement.setAttribute("ContentType",
                        "application/vnd.openxmlformats-package.digital-signature-origin");
                typesElement.appendChild(defaultElement);
            }

            writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false);
        } else if ("_rels/.rels".equals(zipEntry.getName())) {
            Document relsDocument = loadDocumentNoClose(zipInputStream);

            Element nsElement = relsDocument.createElement("ns");
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
                    "http://schemas.openxmlformats.org/package/2006/relationships");
            NodeList nodeList = XPathAPI.selectNodeList(relsDocument,
                    "/tns:Relationships/tns:Relationship[@Target='_xmlsignatures/origin.sigs']", nsElement);
            if (0 == nodeList.getLength()) {
                Element relationshipElement = relsDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship");
                relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString());
                relationshipElement.setAttribute("Type",
                        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin");
                relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs");

                relsDocument.getDocumentElement().appendChild(relationshipElement);
            }

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if ("_xmlsignatures/_rels/origin.sigs.rels".equals(zipEntry.getName())) {
            hasOriginSigsRels = true;
            Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            Element relationshipElement = originSignRelsDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship");
            String relationshipId = "rel-" + UUID.randomUUID().toString();
            relationshipElement.setAttribute("Id", relationshipId);
            relationshipElement.setAttribute("Type",
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature");
            String target = FilenameUtils.getName(signatureZipEntryName);
            LOG.debug("target: " + target);
            relationshipElement.setAttribute("Target", target);
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

            writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
        } else {
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }

    if (false == hasOriginSigsRels) {
        /*
         * Add signature relationships document.
         */
        addOriginSigsRels(signatureZipEntryName, zipOutputStream);
        addOriginSigs(zipOutputStream);
    }

    /*
     * Return.
     */
    zipInputStream.close();
    return zipOutputStream;
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????./*  ww  w . ja  v a  2s . com*/
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

    // Dsig??
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return DcCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:edu.wpi.margrave.MCommunicator.java

/**
 * We suspended stdin and stdout. Append what has accumulated to the response.
 * @param theResponse/*from  w  w w .  j  av a2  s .  com*/
 */
protected static void addBuffers(Document theResponse) {
    // add in any supplemental or error information
    Element envOutChild = theResponse.createElementNS(null, "EXTRA-OUT");
    envOutChild.appendChild(theResponse.createTextNode(MEnvironment.outBuffer.toString()));
    Element envErrChild = theResponse.createElementNS(null, "EXTRA-ERR");
    envErrChild.appendChild(theResponse.createTextNode(MEnvironment.errorBuffer.toString()));

    // Clear out the "out" and "error" buffers.
    MEnvironment.errorBuffer.getBuffer().setLength(0);
    MEnvironment.outBuffer.getBuffer().setLength(0);

    theResponse.getDocumentElement().appendChild(envOutChild);
    theResponse.getDocumentElement().appendChild(envErrChild);
}

From source file:org.ambraproject.article.service.ArticleDocumentServiceImpl.java

@SuppressWarnings("unchecked")
private void appendJournals(URI articleId, Document doc) throws NoSuchArticleIdException {

    Set<Journal> journals;//from www  . j av a 2  s.co  m
    try {
        journals = ((Article) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class)
                .setFetchMode("journals", FetchMode.JOIN).add(Restrictions.eq("doi", articleId.toString())))
                .get(0)).getJournals();
    } catch (IndexOutOfBoundsException e) {
        throw new NoSuchArticleIdException(articleId.toString());
    }

    Element additionalInfoElement = doc.createElementNS(XML_NAMESPACE, "ambra");
    Element journalsElement = doc.createElementNS(XML_NAMESPACE, "journals");

    doc.getDocumentElement().appendChild(additionalInfoElement);
    additionalInfoElement.appendChild(journalsElement);

    for (Journal journal : journals) {
        Element journalElement = doc.createElementNS(XML_NAMESPACE, "journal");

        Element eIssn = doc.createElementNS(XML_NAMESPACE, "eIssn");
        eIssn.appendChild(doc.createTextNode(journal.geteIssn()));
        journalElement.appendChild(eIssn);

        Element key = doc.createElementNS(XML_NAMESPACE, "key");
        key.appendChild(doc.createTextNode(journal.getJournalKey()));
        journalElement.appendChild(key);

        Element name = doc.createElementNS(XML_NAMESPACE, "name");
        name.appendChild(doc.createTextNode(journal.getTitle()));
        journalElement.appendChild(name);

        journalsElement.appendChild(journalElement);
    }
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????.// w w  w  . ja v  a  2s  .c  om
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

    // Dsig??
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return PersoniumCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:com.evolveum.midpoint.prism.marshaller.ItemPathHolder.java

public Element toElement(String elementNamespace, String localElementName, Document document) {
    Element element = document.createElementNS(elementNamespace, localElementName);
    if (!StringUtils.isBlank(elementNamespace)) {
        String prefix = GlobalDynamicNamespacePrefixMapper.getPreferredPrefix(elementNamespace);
        if (!StringUtils.isBlank(prefix)) {
            try {
                element.setPrefix(prefix);
            } catch (DOMException e) {
                throw new SystemException("Error setting XML prefix '" + prefix + "' to element {"
                        + elementNamespace + "}" + localElementName + ": " + e.getMessage(), e);
            }/*from w w  w. j av  a2 s  .com*/
        }
    }
    element.setTextContent(getXPathWithDeclarations());
    Map<String, String> namespaceMap = getNamespaceMap();
    if (namespaceMap != null) {
        for (Entry<String, String> entry : namespaceMap.entrySet()) {
            DOMUtil.setNamespaceDeclaration(element, entry.getKey(), entry.getValue());
        }
    }
    return element;
}

From source file:com.rest4j.generator.Generator.java

public void generate() throws Exception {
    ApiFactory fac = new ApiFactory(apiXml, null, null);
    for (String className : preprocessors) {
        Preprocessor p = (Preprocessor) Class.forName(className).newInstance();
        fac.addPreprocessor(p);//from   www .jav a  2 s .  c o  m
    }
    Document xml = fac.getDocument();
    preprocess(xml);
    URL url = getStylesheet();

    String filename = "index.html";
    for (TemplateParam param : params) {
        if (param.getName().equals("filename")) {
            filename = param.getValue();
        }
    }

    Document doc = transform(xml, url);
    cleanupBeforePostprocess(doc.getDocumentElement());

    if (postprocessingXSLT != null) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document composed = documentBuilder.newDocument();
        org.w3c.dom.Element top = composed.createElementNS("http://rest4j.com/api-description", "top");

        composed.appendChild(top);
        top.appendChild(composed.adoptNode(xml.getDocumentElement()));
        top.appendChild(composed.adoptNode(doc.getDocumentElement()));

        xml = null;
        doc = null; // free some mem

        doc = transform(composed, postprocessingXSLT);
    }

    if ("files".equals(doc.getDocumentElement().getLocalName())) {
        // break the result into files
        for (Node child : Util.it(doc.getDocumentElement().getChildNodes())) {
            if ("file".equals(child.getLocalName())) {
                if (child.getAttributes().getNamedItem("name") == null) {
                    throw new IllegalArgumentException("Attribute name not found in <file>");
                }
                String name = child.getAttributes().getNamedItem("name").getTextContent();
                File file = new File(outputDir, name);
                file.getParentFile().mkdirs();
                System.out.println("Write " + file.getAbsolutePath());
                Attr copyFromAttr = (Attr) child.getAttributes().getNamedItem("copy-from");
                if (copyFromAttr == null) {
                    cleanupFinal((Element) child);
                    if (child.getAttributes().getNamedItem("text") != null) {
                        // plain-text output
                        FileOutputStream fos = new FileOutputStream(file);
                        try {
                            IOUtils.write(child.getTextContent(), fos, "UTF-8");
                        } finally {
                            IOUtils.closeQuietly(fos);
                        }
                    } else {
                        output(child, file);
                    }
                } else {
                    String copyFrom = copyFromAttr.getValue();
                    URL asset = getClass().getClassLoader().getResource(copyFrom);
                    if (asset == null) {
                        asset = getClass().getResource(copyFrom);
                    }
                    if (asset == null) {
                        File assetFile = new File(copyFrom);
                        if (!assetFile.canRead()) {
                            if (postprocessingXSLT != null) {
                                asset = new URL(postprocessingXSLT, copyFrom);
                                try {
                                    asset.openStream().close();
                                } catch (FileNotFoundException fnfe) {
                                    asset = null;
                                }
                            }
                            if (asset == null) {
                                asset = new URL(getStylesheet(), copyFrom);
                                try {
                                    asset.openStream().close();
                                } catch (FileNotFoundException fnfe) {
                                    asset = null;
                                }
                            }
                            if (asset == null)
                                throw new IllegalArgumentException("File '" + copyFrom
                                        + "' specified by @copy-from not found in the classpath or filesystem");
                        } else {
                            asset = assetFile.toURI().toURL();
                        }
                    }
                    InputStream is = asset.openStream();
                    OutputStream fos = new FileOutputStream(file);
                    try {
                        IOUtils.copy(is, fos);
                    } finally {
                        IOUtils.closeQuietly(is);
                        IOUtils.closeQuietly(fos);
                    }
                }
            } else if (child.getNodeType() == Node.ELEMENT_NODE) {
                throw new IllegalArgumentException("Something but <file> found inside <files>");
            }
        }
    } else {
        File file = new File(outputDir, filename);
        System.out.println("Write " + file.getAbsolutePath());
        cleanupFinal(doc.getDocumentElement());
        DOMSource source = new DOMSource(doc);
        FileOutputStream fos = new FileOutputStream(file);
        try {
            StreamResult result = new StreamResult(fos);
            Transformer trans = tFactory.newTransformer();
            trans.transform(source, result);
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java

/**
 * Builds modsCollection from mods of articles.
 */// w w  w.  j  a  v a 2 s. c  om
Document mergeElements(List<Article> articles) throws DOMException {
    Document doc = db.newDocument();
    Element root = doc.createElementNS(ModsConstants.NS, "modsCollection");
    for (Article article : articles) {
        Element modsElm = article.getModsElement();
        Node n = doc.adoptNode(modsElm);
        root.appendChild(n);
    }
    doc.appendChild(root);
    return doc;
}

From source file:de.bund.bfr.pmfml.numl.ResultComponent.java

/**
 * Builds a {@link ReferenceNuMLNode} using the RIS tag set.
 *//*from www. j a  v a  2s.  com*/
public ReferenceNuMLNode(final Reference reference, final Document doc) {

    // Reference container
    node = doc.createElementNS(DC_URI, TAG);

    if (reference.isSetAuthor()) {
        final Element authorNode = doc.createElement(SPEC.getAuthor());
        authorNode.setTextContent(reference.getAuthor());
        node.appendChild(authorNode);
    }

    if (reference.isSetYear()) {
        final Element yearNode = doc.createElement(SPEC.getYear());
        yearNode.setTextContent(reference.getYear().toString());
        node.appendChild(yearNode);
    }

    if (reference.isSetTitle()) {
        final Element titleNode = doc.createElement(SPEC.getTitle());
        titleNode.setTextContent(reference.getTitle());
        node.appendChild(titleNode);
    }

    if (reference.isSetAbstractText()) {
        final Element abstractNode = doc.createElement(SPEC.getAbstract());
        abstractNode.setTextContent(reference.getAbstractText());
        node.appendChild(abstractNode);
    }

    if (reference.isSetJournal()) {
        final Element journalNode = doc.createElement(SPEC.getJournal());
        journalNode.setTextContent(reference.getJournal());
        node.appendChild(journalNode);
    }

    if (reference.isSetVolume()) {
        final Element volumeNode = doc.createElement(SPEC.getVolume());
        volumeNode.setTextContent(reference.getVolume());
        node.appendChild(volumeNode);
    }

    if (reference.isSetIssue()) {
        final Element issueNode = doc.createElement(SPEC.getIssue());
        issueNode.setTextContent(reference.getIssue());
        node.appendChild(issueNode);
    }

    if (reference.isSetPage()) {
        final Element pageNode = doc.createElement(SPEC.getPage());
        pageNode.setTextContent(reference.getPage().toString());
        node.appendChild(pageNode);
    }

    if (reference.isSetApprovalMode()) {
        final Element approvalNode = doc.createElement(SPEC.getApproval());
        approvalNode.setTextContent(reference.getApprovalMode().toString());
        node.appendChild(approvalNode);
    }

    if (reference.isSetWebsite()) {
        final Element websiteNode = doc.createElement(SPEC.getWebsite());
        websiteNode.setTextContent(reference.getWebsite());
        node.appendChild(websiteNode);
    }

    if (reference.isSetType()) {
        final Element typeNode = doc.createElement(SPEC.getType());
        typeNode.setTextContent(reference.getType().toString());
        node.appendChild(typeNode);
    }

    if (reference.isSetComment()) {
        final Element commentNode = doc.createElement(SPEC.getComment());
        commentNode.setTextContent(reference.getComment());
        node.appendChild(commentNode);
    }
}