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.errorreport.ErrorReport.java

private Document addMarker(String id, Document doc, String xpath) {
    try {//from www . ja  v  a 2s . c o m

        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:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Encode a <code>Boolean</code> in XML with a given XML namespace and tag
 * name. If aBoolean is <code>null</code> an element is not added.
 * /*from ww  w .j av a  2 s.  c  o  m*/
 * @param aDocument
 *            DOM Document of <code>aRoot</code>. This parameter also acts
 *            as a factory for XML elements.
 * @param aRoot
 *            XML Element to add children nodes to. For example, the root
 *            node could be &ltdomain:update&gt
 * @param aBoolean
 *            <code>Boolean</code> to add.
 * @param aNS
 *            XML namespace of the element. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name is
 *            "domain:name".
 * @exception EPPEncodeException
 *                Error encoding the <code>Boolean</code>.
 */
public static void encodeBoolean(Document aDocument, Element aRoot, Boolean aBoolean, String aNS,
        String aTagName) throws EPPEncodeException {
    if (aBoolean != null) {
        Element currElm = aDocument.createElementNS(aNS, aTagName);

        String xmlValue;

        if (aBoolean.booleanValue()) {
            xmlValue = "1";
        } else {
            xmlValue = "0";
        }

        Text currVal = aDocument.createTextNode(xmlValue);

        currElm.appendChild(currVal);
        aRoot.appendChild(currElm);
    }
}

From source file:com.microsoft.windowsazure.management.sql.ServerOperationsImpl.java

/**
* Changes the administrative password of an existing Azure SQL Database
* Server for a given subscription./* ww w .  j  a  v  a 2 s.com*/
*
* @param serverName Required. The name of the Azure SQL Database Server
* that will have the administrator password changed.
* @param parameters Required. The necessary parameters for modifying the
* adminstrator password for a server.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse changeAdministratorPassword(String serverName,
        ServerChangeAdministratorPasswordParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getNewPassword() == null) {
        throw new NullPointerException("parameters.NewPassword");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "changeAdministratorPasswordAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("op=ResetPassword");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element administratorLoginPasswordElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword");
    requestDoc.appendChild(administratorLoginPasswordElement);

    administratorLoginPasswordElement.appendChild(requestDoc.createTextNode(parameters.getNewPassword()));

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:fi.helsinki.lib.simplerest.ItemsResource.java

@Get("html|xhtml|xml")
public Representation toXml() {
    Collection collection = null;
    DomRepresentation representation = null;
    Document d = null;
    try {//from w w  w .  ja  va  2s . co m
        collection = Collection.find(context, this.collectionId);
        if (collection == null) {
            return errorNotFound(context, "Could not find the collection.");
        }

        representation = new DomRepresentation(MediaType.TEXT_HTML);
        d = representation.getDocument();
    } catch (SQLException e) {
        return errorInternal(context, e.toString());
    } catch (IOException e) {
        return errorInternal(context, e.toString());
    }

    Element html = d.createElement("html");
    d.appendChild(html);

    Element head = d.createElement("head");
    html.appendChild(head);

    Element title = d.createElement("title");
    head.appendChild(title);
    title.appendChild(d.createTextNode("Items for collection " + collection.getName()));

    Element body = d.createElement("body");
    html.appendChild(body);

    Element ulItems = d.createElement("ul");
    setId(ulItems, "items");
    body.appendChild(ulItems);

    String base = baseUrl();
    try {
        ItemIterator ii = collection.getItems();
        while (ii.hasNext()) {
            Item item = ii.next();
            Element li = d.createElement("li");
            Element a = d.createElement("a");
            String name = item.getName();
            if (name == null) {
                // FIXME: Should we really give names for items with no
                // FIXME: name? (And if so does "Untitled" make sense?)
                // FIXME: Anyway, this would break with null values.
                name = "Untitled";
            }
            a.appendChild(d.createTextNode(name));
            String href = base + ItemResource.relativeUrl(item.getID());
            setAttribute(a, "href", href);
            li.appendChild(a);
            ulItems.appendChild(li);
        }
    } catch (SQLException e) {
        String errMsg = "SQLException while trying to items of the collection. " + e.getMessage();
        return errorInternal(context, errMsg);
    }

    Element form = d.createElement("form");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("method", "post");
    makeInputRow(d, form, "title", "Title");
    makeInputRow(d, form, "lang", "Language");

    Element submitButton = d.createElement("input");
    submitButton.setAttribute("type", "submit");
    submitButton.setAttribute("value", "Create a new item");
    form.appendChild(submitButton);

    body.appendChild(form);

    try {
        if (context != null) {
            context.complete();
        }
    } catch (SQLException e) {
        log.log(Priority.INFO, e);
    }

    return representation;
}

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

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

    Set<Journal> journals;/*from ww w .  ja  va 2  s  .  com*/
    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:com.microsoft.windowsazure.management.scheduler.CloudServiceManagementClientImpl.java

/**
* EntitleResource is used only for 3rd party Store providers. Each
* subscription must be entitled for the resource before creating that
* particular type of resource./*from  w  w  w.  j a  v  a  2  s. c  om*/
*
* @param parameters Required. Parameters provided to the EntitleResource
* method.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse entitleResource(EntitleResourceParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getResourceNamespace() == null) {
        throw new NullPointerException("parameters.ResourceNamespace");
    }
    if (parameters.getResourceType() == null) {
        throw new NullPointerException("parameters.ResourceType");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "entitleResourceAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/EntitleResource";
    String baseUrl = this.getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2013-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element entitleResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EntitleResource");
    requestDoc.appendChild(entitleResourceElement);

    Element resourceProviderNameSpaceElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceProviderNameSpace");
    resourceProviderNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getResourceNamespace()));
    entitleResourceElement.appendChild(resourceProviderNameSpaceElement);

    Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type");
    typeElement.appendChild(requestDoc.createTextNode(parameters.getResourceType()));
    entitleResourceElement.appendChild(typeElement);

    Element registrationDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "RegistrationDate");
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    registrationDateElement.appendChild(
            requestDoc.createTextNode(simpleDateFormat.format(parameters.getRegistrationDate().getTime())));
    entitleResourceElement.appendChild(registrationDateElement);

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:ddf.metrics.reporting.internal.rrd4j.RrdMetricsRetriever.java

@Override
public String createXmlData(String metricName, String rrdFilename, long startTime, long endTime)
        throws IOException, MetricsGraphException {
    LOGGER.trace("ENTERING: createXmlData");

    MetricData metricData = getMetricData(rrdFilename, startTime, endTime);

    String displayableMetricName = convertCamelCase(metricName);

    String title = displayableMetricName + " for " + getCalendarTime(startTime) + " to "
            + getCalendarTime(endTime);/*  ww  w  . j a v  a  2  s  . c o m*/

    String xmlString = null;

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(metricName);
        doc.appendChild(rootElement);

        Element titleElement = doc.createElement("title");
        titleElement.appendChild(doc.createTextNode(title));
        rootElement.appendChild(titleElement);

        Element dataElement = doc.createElement("data");
        rootElement.appendChild(dataElement);

        List<Long> timestamps = metricData.getTimestamps();
        List<Double> values = metricData.getValues();

        for (int i = 0; i < timestamps.size(); i++) {
            Element sampleElement = doc.createElement("sample");
            dataElement.appendChild(sampleElement);

            String timestamp = getCalendarTime(timestamps.get(i));
            Element timestampElement = doc.createElement("timestamp");
            timestampElement.appendChild(doc.createTextNode(timestamp));
            sampleElement.appendChild(timestampElement);

            Element valueElement = doc.createElement("value");
            valueElement.appendChild(doc.createTextNode(String.valueOf(values.get(i))));
            sampleElement.appendChild(valueElement);
        }

        if (metricData.hasTotalCount()) {
            Element totalCountElement = doc.createElement("totalCount");
            totalCountElement.appendChild(doc.createTextNode(Long.toString(metricData.getTotalCount())));
            dataElement.appendChild(totalCountElement);
        }

        // Write the content into xml stringwriter
        xmlString = XMLUtils.prettyFormat(doc);
    } catch (ParserConfigurationException pce) {
        LOGGER.error("Parsing error while creating xml data", pce);
    }

    LOGGER.trace("xml = {}", xmlString);

    LOGGER.trace("EXITING: createXmlData");

    return xmlString;
}

From source file:com.msopentech.odatajclient.engine.data.impl.JSONPropertyDeserializer.java

@Override
protected JSONProperty doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    final JSONProperty property = new JSONProperty();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }/*from  ww  w  . j av a  2s . c o  m*/

    try {
        final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        if (property.getMetadata() != null) {
            final String metadataURI = property.getMetadata().toASCIIString();
            final int dashIdx = metadataURI.lastIndexOf('#');
            if (dashIdx != -1) {
                content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
            }
        }

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            JSONDOMTreeUtils.buildSubtree(client, content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java

private Element feed(final AtomFeed feed) throws ParserConfigurationException {
    final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element feedElem = doc.createElement(ODataConstants.ATOM_ELEM_FEED);
    feedElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    feedElem.setAttribute(ODataConstants.XMLNS_METADATA,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA));
    feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES));
    feedElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    feedElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (feed.getBaseURI() != null) {
        feedElem.setAttribute(ODataConstants.ATTR_XMLBASE, feed.getBaseURI().toASCIIString());
    }//from   w  w  w.j a  va  2  s . c  o  m
    doc.appendChild(feedElem);

    if (StringUtils.isNotBlank(feed.getTitle())) {
        final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
        title.appendChild(doc.createTextNode(feed.getTitle()));
        feedElem.appendChild(title);
    }

    if (StringUtils.isNotBlank(feed.getSummary())) {
        final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
        summary.appendChild(doc.createTextNode(feed.getSummary()));
        feedElem.appendChild(summary);
    }

    for (AtomEntry entry : feed.getEntries()) {
        feedElem.appendChild(doc.importNode(entry(entry), true));
    }

    return feedElem;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToXML.java

/**
 * Creates a dom element//from w  ww  . ja  va  2 s.  c  o  m
 * @param elementName
 * @param elementValue
 * @param dom
 * @return
 */
private 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;
}