Example usage for org.w3c.dom Document createElement

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

Introduction

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

Prototype

public Element createElement(String tagName) throws DOMException;

Source Link

Document

Creates an element of the type specified.

Usage

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

public static Document convertToDOM(TWorkItemBean documentItem, Integer personID, Locale locale) {
    Document dom = null;
    try {//from  ww w.j  a  va 2  s.c om
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        dom = builder.newDocument();
    } catch (FactoryConfigurationError e) {
        LOGGER.error("Creating the DOM document failed with FactoryConfigurationError:" + e.getMessage());
        return null;
    } catch (ParserConfigurationException e) {
        LOGGER.error("Creating the DOM document failed with ParserConfigurationException: " + e.getMessage());
        return null;
    }
    Element root = dom.createElement(CUSTOM_XML_ELEMENTS.MAIN_ELEMENT);
    if (documentItem != null) {
        Integer itemID = documentItem.getObjectID();
        List<TWorkItemBean> itemList = new LinkedList<TWorkItemBean>();
        itemList.add(documentItem);
        List<ReportBean> reportBeansList = LoadItemIDListItems.getReportBeansByWorkItems(itemList, personID,
                locale, true, false, false, false, false, false, false, false, false);
        ReportBean showableWorkItem = reportBeansList.get(0);
        Map<Integer, String> showValuesMap = showableWorkItem.getShowValuesMap();
        if (showValuesMap != null) {
            List<TFieldBean> fieldBeansList = FieldBL.loadAll();
            for (TFieldBean fieldBean : fieldBeansList) {
                Integer fieldID = fieldBean.getObjectID();
                String fieldName = fieldBean.getName();
                String showValue = showValuesMap.get(fieldID);
                if (showValue != null && !"".equals(showValue)) {
                    IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
                    if (fieldTypeRT != null) {
                        if (fieldTypeRT.isLong()) {
                            showValue = StringEscapeUtils.escapeHtml4(showValue);
                        }
                    }
                    appendChild(root, fieldName, showValue, dom);
                    appendChild(root, fieldName + CUSTOM_XML_ELEMENTS.PRESENT_SUFFIX, Boolean.TRUE.toString(),
                            dom);
                } else {
                    appendChild(root, fieldName + CUSTOM_XML_ELEMENTS.PRESENT_SUFFIX, Boolean.FALSE.toString(),
                            dom);
                    appendChild(root, fieldName, "", dom);
                }
            }

            List<TPersonBean> consultedPersonBeans = PersonBL.getDirectConsultants(itemID);
            addWatcherNodes(consultedPersonBeans, root, dom, CUSTOM_XML_ELEMENTS.CONSULTED_LIST,
                    CUSTOM_XML_ELEMENTS.CONSULTED_PERSON);
            List<TPersonBean> informedPersonBeans = PersonBL.getDirectInformants(itemID);
            addWatcherNodes(informedPersonBeans, root, dom, CUSTOM_XML_ELEMENTS.INFORMED_LIST,
                    CUSTOM_XML_ELEMENTS.INFORMED_PERSON);

            List<HistoryValues> comments = HistoryLoaderBL.getRestrictedWorkItemComments(personID, itemID,
                    locale, false, /*LONG_TEXT_TYPE.ISPLAIN*/ LONG_TEXT_TYPE.ISFULLHTML);
            addCommentNodes(comments, root, dom, locale);

        }
    }
    dom.appendChild(root);
    return dom;
}

From source file:com.photon.phresco.framework.commons.QualityUtil.java

private static void createHeaderElementProp(Document document, Map<String, String> headersMap,
        Node collectionProp) {/*from w  w  w .  java2s  .  c o m*/
    for (Map.Entry<String, String> entry : headersMap.entrySet()) {
        Node subElementProp = document.createElement("elementProp");
        NamedNodeMap subElementAttributes = subElementProp.getAttributes();
        subElementAttributes.setNamedItem(createAttribute(document, "name", ""));
        subElementAttributes.setNamedItem(createAttribute(document, "elementType", "Header"));
        collectionProp.appendChild(subElementProp);
        appendTypeProp(document, subElementProp, "stringProp", "Header.name", entry.getKey());
        appendTypeProp(document, subElementProp, "stringProp", "Header.value", entry.getValue());
    }
}

From source file:Main.java

/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node./*  ww w .j a v  a 2  s.  c  o m*/
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start = src;
    Node parent = src;
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl) element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:com.photon.phresco.framework.commons.QualityUtil.java

private static Node appendHttpSamplerProxy(Document document, Node hashTree, String name, String context,
        String contextType, String contextPostData, String encodingType) {
    Node httpSamplerProxy = document.createElement("HTTPSamplerProxy");
    String contentEncoding = null;
    if (contextType.equals(FrameworkConstants.POST)) {
        contentEncoding = encodingType;//  ww w  .  ja  v a2s  . c  om
    }

    NamedNodeMap attributes = httpSamplerProxy.getAttributes();
    attributes.setNamedItem(createAttribute(document, "guiclass", "HttpTestSampleGui"));
    attributes.setNamedItem(createAttribute(document, "testclass", "HTTPSamplerProxy"));
    attributes.setNamedItem(createAttribute(document, "testname", name)); //url name
    attributes.setNamedItem(createAttribute(document, "enabled", "true"));

    appendElementProp(document, httpSamplerProxy, contextType, contextPostData);

    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.domain", null);
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.port", null);
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.connect_timeout", null);
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.response_timeout", null);
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.protocol", null);
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.contentEncoding", contentEncoding);
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.path", context); // server url
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.method", contextType);

    appendTypeProp(document, httpSamplerProxy, "boolProp", "HTTPSampler.follow_redirects", "false");
    appendTypeProp(document, httpSamplerProxy, "boolProp", "HTTPSampler.auto_redirects", "true");
    appendTypeProp(document, httpSamplerProxy, "boolProp", "HTTPSampler.use_keepalive", "true");
    appendTypeProp(document, httpSamplerProxy, "boolProp", "HTTPSampler.DO_MULTIPART_POST", "false");

    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.implementation", "Java");
    appendTypeProp(document, httpSamplerProxy, "boolProp", "HTTPSampler.monitor", "false");
    appendTypeProp(document, httpSamplerProxy, "stringProp", "HTTPSampler.embedded_url_re", null);

    return httpSamplerProxy;
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries CoNE service and returns the result as DOM node.
 * The returned XML has the following structure:
 * <cone>/*from   w  ww.ja  v  a2s .  c  o m*/
 *   <author>
 *     <familyname>Buxtehude-Mlln</familyname>
 *     <givenname>Heribert</givenname>
 *     <prefix>von und zu</prefix>
 *     <title>Knig</title>
 *   </author>
 *   <author>
 *     <familyname>Mller</familyname>
 *     <givenname>Peter</givenname>
 *   </author>
 * </authors>
 * 
 * @param authors
 * @return 
 */
// IMPORTANT!!! Currently not working due to missing userHnadle info
public static Node queryCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl = null;
    try {
        System.out.println("queryCone: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&q="
                + URLEncoder.encode(query, "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);

        if (method.getStatusCode() == 200) {
            String[] results = method.getResponseBodyAsString().split("\n");
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO");
                    logger.info(detailMethod.getPath());
                    logger.info(detailMethod.getQueryString());

                    if (coneSession != null) {
                        detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
                    }
                    ProxyHelper.executeMethod(client, detailMethod);

                    if (detailMethod.getStatusCode() == 200) {
                        Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                        element.appendChild(document.importNode(details.getFirstChild(), true));
                    } else {
                        logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                + detailMethod.getResponseBodyAsString());
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }

        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. (" + queryUrl
                + ") .Otherwise it should be clarified if any measures have to be taken.");
        logger.debug("Stacktrace", e);
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * /*  ww w .  j ava 2s.c  o  m*/
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) {
    DocumentBuilder documentBuilder;

    try {
        System.out.println("queryConeExact: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:identifier/rdf:value=\"" + URLEncoder.encode(identifier, "UTF-8")
                + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8") + "";
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            Set<String> oldIds = new HashSet<String>();
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    if (!oldIds.contains(id)) {
                        GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO");

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + "TODO"
                                + " returned " + detailMethod.getResponseBodyAsString());
                        if (detailMethod.getStatusCode() == 200) {
                            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                            element.appendChild(document.importNode(details.getFirstChild(), true));
                        } else {
                            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                    + detailMethod.getResponseBodyAsString());
                        }
                        oldIds.add(id);
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * /*from  w  ww  .  ja  v  a  2s . c om*/
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExact(String model, String name, String ou) {
    DocumentBuilder documentBuilder;

    try {
        System.out.println("queryConeExact: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:title=\"" + URLEncoder.encode(name, "UTF-8")
                + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8") + "";
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                    + "/query?format=jquery&dcterms:alternative=\"" + URLEncoder.encode(name, "UTF-8")
                    + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8");
            client = new HttpClient();
            method = new GetMethod(queryUrl);
            if (coneSession != null) {
                method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
            }
            ProxyHelper.executeMethod(client, method);
            logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
            if (method.getStatusCode() == 200) {
                results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
                Set<String> oldIds = new HashSet<String>();
                for (String result : results) {
                    if (!"".equals(result.trim())) {
                        String id = result.split("\\|")[1];
                        if (!oldIds.contains(id)) {
                            GetMethod detailMethod = new GetMethod(
                                    id + "?format=rdf&eSciDocUserHandle=" + "TODO");

                            ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                            client.executeMethod(detailMethod);
                            logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + "TODO"
                                    + " returned " + detailMethod.getResponseBodyAsString());
                            if (detailMethod.getStatusCode() == 200) {
                                Document details = documentBuilder
                                        .parse(detailMethod.getResponseBodyAsStream());
                                element.appendChild(document.importNode(details.getFirstChild(), true));
                            } else {
                                logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode()
                                        + "\n" + detailMethod.getResponseBodyAsString());
                            }
                            oldIds.add(id);
                        }
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:com.connexta.arbitro.utils.PolicyUtils.java

/**
 * This method creates a policy element of the XACML policy
 * @param policyElementDTO  policy element data object
 * @param doc XML document/* w  w w .  jav  a2 s. c o m*/
 * @return policyElement
 * @throws PolicyBuilderException if
 */

public static Element createPolicyElement(PolicyElementDTO policyElementDTO, Document doc)
        throws PolicyBuilderException {

    Element policyElement = doc.createElement(PolicyConstants.POLICY_ELEMENT);

    policyElement.setAttribute("xmlns", PolicyConstants.XACMLData.XACML3_POLICY_NAMESPACE);

    if (policyElementDTO.getPolicyName() != null && policyElementDTO.getPolicyName().trim().length() > 0) {
        policyElement.setAttribute(PolicyConstants.POLICY_ID, policyElementDTO.getPolicyName());
    } else {
        throw new PolicyBuilderException("Policy name can not be null");
    }

    if (policyElementDTO.getRuleCombiningAlgorithms() != null
            && policyElementDTO.getRuleCombiningAlgorithms().trim().length() > 0) {
        policyElement.setAttribute(PolicyConstants.RULE_ALGORITHM,
                policyElementDTO.getRuleCombiningAlgorithms());
    } else {
        policyElement.setAttribute(PolicyConstants.RULE_ALGORITHM,
                PolicyConstants.RuleCombiningAlog.DENY_OVERRIDE_ID); // TODO
        log.warn("Rule combining algorithm is not defined. Use default algorithm; Deny Override");
    }

    if (policyElementDTO.getVersion() != null && policyElementDTO.getVersion().trim().length() > 0) {
        policyElement.setAttribute(PolicyConstants.POLICY_VERSION, policyElementDTO.getVersion());
    } else {
        // policy version is can be handled by policy registry.  therefore we can ignore it, although it
        // is a required attribute
        policyElement.setAttribute(PolicyConstants.POLICY_VERSION, "1.0");
    }

    if (policyElementDTO.getPolicyDescription() != null
            && policyElementDTO.getPolicyDescription().trim().length() > 0) {

        Element descriptionElement = doc.createElement(PolicyConstants.DESCRIPTION_ELEMENT);
        descriptionElement.setTextContent(policyElementDTO.getPolicyDescription());
        policyElement.appendChild(descriptionElement);
    }

    TargetElementDTO targetElementDTO = policyElementDTO.getTargetElementDTO();
    List<RuleElementDTO> ruleElementDTOs = policyElementDTO.getRuleElementDTOs();
    List<ObligationElementDTO> obligationElementDTOs = policyElementDTO.getObligationElementDTOs();

    if (targetElementDTO != null) {
        policyElement.appendChild(createTargetElement(targetElementDTO, doc));
    } else {
        policyElement.appendChild(doc.createElement(PolicyConstants.TARGET_ELEMENT));
    }

    if (ruleElementDTOs != null && ruleElementDTOs.size() > 0) {
        for (RuleElementDTO ruleElementDTO : ruleElementDTOs) {
            policyElement.appendChild(createRuleElement(ruleElementDTO, doc));
        }
    } else {
        RuleElementDTO ruleElementDTO = new RuleElementDTO();
        ruleElementDTO.setRuleId(UUID.randomUUID().toString());
        ruleElementDTO.setRuleEffect(PolicyConstants.RuleEffect.DENY);
        policyElement.appendChild(createRuleElement(ruleElementDTO, doc));
    }

    if (obligationElementDTOs != null && obligationElementDTOs.size() > 0) {
        List<ObligationElementDTO> obligations = new ArrayList<ObligationElementDTO>();
        List<ObligationElementDTO> advices = new ArrayList<ObligationElementDTO>();
        for (ObligationElementDTO obligationElementDTO : obligationElementDTOs) {
            if (obligationElementDTO.getType() == ObligationElementDTO.ADVICE) {
                advices.add(obligationElementDTO);
            } else {
                obligations.add(obligationElementDTO);
            }
        }
        Element obligation = createObligationsElement(obligations, doc);
        Element advice = createAdvicesElement(advices, doc);
        if (obligation != null) {
            policyElement.appendChild(obligation);
        }
        if (advice != null) {
            policyElement.appendChild(advice);
        }
    }

    return policyElement;
}

From source file:edu.indiana.lib.twinpeaks.util.DomUtils.java

/**
 * Start a new XML Document.//from   ww  w. j  av  a2 s. c  o  m
 * @param rootName The name of the Document root Element (created here)
 * @return the Document
 * @throws DomException
 */
public static Document createXmlDocument(String rootName) throws DomException {
    try {
        Document document = getXmlDocumentBuilder().newDocument();
        Element root = document.createElement(rootName);

        document.appendChild(root);
        return document;

    } catch (Exception e) {
        throw new DomException(e.toString());
    }
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

private static Element toCollectionPropertyElement(final ODataProperty prop, final Document doc,
        final boolean setType) {

    if (!prop.hasCollectionValue()) {
        throw new IllegalArgumentException(
                "Invalid property value type " + prop.getValue().getClass().getSimpleName());
    }/*from  w  w  w. j ava2  s  . c  om*/

    final ODataCollectionValue value = prop.getCollectionValue();

    final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + prop.getName());
    if (value.getTypeName() != null && setType) {
        element.setAttribute(ODataConstants.ATTR_M_TYPE, value.getTypeName());
    }

    for (ODataValue el : value) {
        if (el.isPrimitive()) {
            element.appendChild(
                    toPrimitivePropertyElement(ODataConstants.ELEM_ELEMENT, el.asPrimitive(), doc, setType));
        } else {
            element.appendChild(
                    toComplexPropertyElement(ODataConstants.ELEM_ELEMENT, el.asComplex(), doc, setType));
        }
    }

    return element;
}