Example usage for org.w3c.dom Node DOCUMENT_NODE

List of usage examples for org.w3c.dom Node DOCUMENT_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node DOCUMENT_NODE.

Prototype

short DOCUMENT_NODE

To view the source code for org.w3c.dom Node DOCUMENT_NODE.

Click Source Link

Document

The node is a Document.

Usage

From source file:org.jbpm.bpel.xml.util.XmlUtil.java

public static void setObjectValue(Element elem, Object value) {
    if (value instanceof Node) {
        switch (((Node) value).getNodeType()) {
        case Node.ELEMENT_NODE:
            // replace element
            copy(elem, (Element) value);
            break;
        case Node.DOCUMENT_NODE:
            // replace element
            copy(elem, ((Document) value).getDocumentElement());
            break;
        default://from   w  w w . jav a  2 s  .co m
            // replace content
            setStringValue(elem, ((Node) value).getNodeValue());
        }
    } else if (value instanceof EndpointReference) {
        // replace element
        ((EndpointReference) value).writeServiceRef(elem);
    } else {
        // replace content
        setStringValue(elem, DatatypeUtil.toString(value));
    }
}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Appends a node and it's children to the given StringBuffer. Indentation is added on recursion.
 *//*w  ww . jav a2 s  .c o  m*/
public static void appendNode(final Node node, final String indent, final StringBuffer sb) {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE: {
        sb.append("<?xml version=\"1.0\"?>\n");

        final Document doc = (Document) node;
        appendNode(doc.getDocumentElement(), "", sb);

        break;
    }

    case Node.ELEMENT_NODE: {
        final String name = node.getNodeName();
        sb.append(indent + "<" + name);

        final NamedNodeMap attributes = node.getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {
            final Node current = attributes.item(i);
            sb.append(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\"");
        }

        sb.append(">");

        // Kinder durchgehen
        final NodeList children = node.getChildNodes();

        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                appendNode(children.item(i), indent, sb);
            }
        }

        sb.append(indent + "</" + name + ">");

        break;
    }

    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE: {
        final String trimmed = node.getNodeValue().trim();

        if (!trimmed.equals("")) {
            sb.append(indent + trimmed);
        }

        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE:
        break;

    case Node.ENTITY_REFERENCE_NODE:
        break;

    case Node.DOCUMENT_TYPE_NODE:
        break;
    }
}

From source file:org.n52.ifgicopter.spf.xml.XMLTools.java

/**
 * //  w w w  .j a v a 2s.  co  m
 * Serializes the given XML tree to string form, including the standard 
 * XML header and indentation if desired. This method relies on the 
 * serialization API from Apache Xerces, since JAXP has on equivalent.
 *
 * @param xml
 *        The XML tree to serialize.
 * 
 * @param printHeader
 *        True if you want the XML header printed before the XML.
 * 
 * @param printIndents
 *        True if you want pretty-printing - child elements will be 
 *        indented with symmetry.
 * 
 * @return The string representation of the given Node.
 * 
 */
public static String toString(Node xml, boolean printHeader, boolean printIndents) {
    short type = xml.getNodeType();

    if (type == Node.TEXT_NODE)
        return xml.getNodeValue();

    //
    // NOTE: This serialization code is not part of JAXP/DOM - it is 
    //       specific to Xerces and creates a Xerces dependency for 
    //       this class.
    //
    XMLSerializer serializer = new XMLSerializer();
    serializer.setNamespaces(true);

    OutputFormat formatter = new OutputFormat();
    formatter.setOmitXMLDeclaration(!printHeader);
    formatter.setIndenting(printIndents);
    serializer.setOutputFormat(formatter);

    StringWriter writer = new StringWriter();
    serializer.setOutputCharStream(writer);

    try {
        if (type == Node.DOCUMENT_NODE)
            serializer.serialize((Document) xml);

        else
            serializer.serialize((Element) xml);
    }

    //
    // we are using a StringWriter, so this "should never happen". the 
    // StringWriter implementation writes to a StringBuffer, so there's 
    // no file I/O that could fail.
    //
    // if it DOES fail, we re-throw with a more serious error, because 
    // this a very common operation.
    //
    catch (IOException error) {
        throw new RuntimeException(error.getMessage(), error);
    }

    return writer.toString();
}

From source file:org.opensingular.internal.lib.commons.xml.MDocument.java

public static MDocument toMDocument(Node no) {
    if (no == null) {
        return null;
    } else if (no instanceof MDocument) {
        return (MDocument) no;
    } else if (no.getNodeType() != Node.DOCUMENT_NODE) {
        throw new SingularException("no " + XPathToolkit.getFullPath(no) + " no  Document");
    }/*from  w w w. ja  va  2s  . c o m*/
    return new MDocumentWrapper((Document) no);
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlMapper.java

/**
 * utility class, hides the implementation as a HashMap
 * @param node//from  w  w w.j a v  a 2 s.c  o  m
 * @return HashMap
 */
private static HashMap hashNode(Node node) {
    HashMap hNode = new HashMap();

    int nType = node.getNodeType();
    NodeList nodes = node.getChildNodes();
    NamedNodeMap attributes = node.getAttributes();
    String name = node.getNodeName();

    // node is a document, recurse
    if (nType == Node.DOCUMENT_NODE) {
        // find root node
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                // find  and process root node
                Node rnode = nodes.item(i);
                if (rnode.getNodeType() == Node.ELEMENT_NODE) {
                    hNode = hashNode(rnode);

                    break;
                }
            }
        }
    }

    //end if Node.DOCUMENT_NODE
    if (nType == Node.ELEMENT_NODE) {
        // add in child elements
        if (nodes != null) {
            for (int j = 0; j < nodes.getLength(); j++) {
                Node cnode = nodes.item(j);
                if (cnode.getNodeType() == Node.ELEMENT_NODE) {
                    String cname = cnode.getNodeName();
                    String ctext = ""; //textValue(cnode);
                    String ctype = getTypeAttribute(cnode);
                    //            log.debug(cname + "=" + ctype);

                    StringBuilder ctextbuf = new StringBuilder();
                    // if we have multiple identical entries store them in a List
                    if ("list".equals(ctype)) {
                        ArrayList list;
                        // if this element name already has a list
                        if (hNode.get(cname) instanceof ArrayList) {
                            list = (ArrayList) hNode.get(cname);
                        } else // put it in a new list
                        {
                            list = new ArrayList();
                        }

                        // support for deep copy

                        //              list.add(ctext);
                        NodeList ccnodes = cnode.getChildNodes();

                        for (int n = 0; n < ccnodes.getLength(); n++) {
                            ctextbuf.append(XmlUtil.getDOMString(ccnodes.item(n)));
                        }
                        ctext = ctextbuf.toString();
                        list.add(ctext);
                        hNode.put(cname, list);
                    } else // scalar (default)
                    {
                        // support for deep copy
                        NodeList ccnodes = cnode.getChildNodes();
                        for (int n = 0; n < ccnodes.getLength(); n++) {
                            ctextbuf.append(XmlUtil.getDOMString(ccnodes.item(n)));
                        }
                        ctext = ctextbuf.toString();
                        hNode.put(cname, ctext);
                    }
                }
            }
        }

        // add in attributes
        if (attributes != null) {
            for (int i = 0; i < attributes.getLength(); i++) {
                Node current = attributes.item(i);
                hNode.put(ATTRIBUTE_PREFIX + current.getNodeName(), current.getNodeValue());
            }
        }
    }

    return hNode;
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlUtil.java

/**
 * Get a textual representation of a Node.
 * @param node The Node// ww  w . j av a 2  s  .c  o  m
 * @return the document in a text string
 */
public static String getDOMString(Node node) {
    //String domString = "";

    StringBuilder domStringbuf = new StringBuilder();

    int type = node.getNodeType();
    switch (type) {
    // print the document element
    case Node.DOCUMENT_NODE: {
        domStringbuf.append("<?xml version=\"1.0\" ?>\n");
        domStringbuf.append(getDOMString(((Document) node).getDocumentElement()));
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        domStringbuf.append("<");
        domStringbuf.append(node.getNodeName());
        NamedNodeMap attrs = node.getAttributes();

        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            //domString += (" " + attr.getNodeName().trim() +
            //              "=\"" + attr.getNodeValue().trim() +
            //              "\"");

            domStringbuf.append((" " + attr.getNodeName().trim() + "=\"" + attr.getNodeValue().trim() + "\""));
        }
        //domString = domStringbuf.toString();
        domStringbuf.append(">");

        NodeList children = node.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++)
                domStringbuf.append(getDOMString(children.item(i)));
        }
        domStringbuf.append("</");
        domStringbuf.append(node.getNodeName());
        domStringbuf.append(">\n");

        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        domStringbuf.append("&");
        domStringbuf.append(node.getNodeName().trim());
        domStringbuf.append(";");

        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        domStringbuf.append("");
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        String val = node.getNodeValue();
        if (val == null)
            val = "";
        domStringbuf.append(val);//rshastri .trim() removed SAK-1671 
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        domStringbuf.append("");
        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        domStringbuf.append("\n");
    }

    String domString = domStringbuf.toString();
    return domString;
}

From source file:org.springframework.oxm.xmlbeans.XmlBeansMarshaller.java

@Override
protected final void marshalDomNode(Object graph, Node node) throws XmlMappingException {
    Document document = node.getNodeType() == Node.DOCUMENT_NODE ? (Document) node : node.getOwnerDocument();
    Node xmlBeansNode = ((XmlObject) graph).newDomNode(getXmlOptions());
    NodeList xmlBeansChildNodes = xmlBeansNode.getChildNodes();
    for (int i = 0; i < xmlBeansChildNodes.getLength(); i++) {
        Node xmlBeansChildNode = xmlBeansChildNodes.item(i);
        Node importedNode = document.importNode(xmlBeansChildNode, true);
        node.appendChild(importedNode);/*from   w  w  w. j  a v  a 2  s  .c  o m*/
    }
}

From source file:org.wso2.carbon.humantask.core.engine.runtime.xpath.XPathExpressionRuntime.java

/**
 * Evaluate XPath expression/*w  w  w. ja  v a 2 s  .com*/
 *
 * @param exp     XPath expression string
 * @param evalCtx Evaluation context containing all the required context information
 * @return Return List of selected nodes or string
 */
@Override
public List evaluate(String exp, EvaluationContext evalCtx) {
    List result;
    Object someRes;
    try {
        someRes = evaluate(exp, evalCtx, XPathConstants.NODESET);
    } catch (Exception e) {
        someRes = evaluate(exp, evalCtx, XPathConstants.STRING);
    }
    if (someRes instanceof List) {
        result = (List) someRes;
        if (log.isDebugEnabled()) {
            log.debug("Returned list of size " + result.size());
        }

        if ((result.size() == 1) && !(result.get(0) instanceof Node)) {
            // Dealing with a Java class
            Object simpleType = result.get(0);
            // Dates get a separate treatment as we don't want to call toString on them
            String textVal;
            if (simpleType instanceof Date) {
                textVal = ISO8601DateParser.format((Date) simpleType);
            } else if (simpleType instanceof DurationValue) {
                textVal = ((DurationValue) simpleType).getStringValue();
            } else {
                textVal = simpleType.toString();
            }

            // Wrapping in a document
            Document document = DOMUtils.newDocument();
            // Giving our node a parent just in case it's an LValue expression
            Element wrapper = document.createElement("wrapper");
            Text text = document.createTextNode(textVal);
            wrapper.appendChild(text);
            document.appendChild(wrapper);
            result = Collections.singletonList(text);
        }
    } else if (someRes instanceof NodeList) {
        NodeList retVal = (NodeList) someRes;
        if (log.isDebugEnabled()) {
            log.debug("Returned node list of size " + retVal.getLength());
        }
        result = new ArrayList(retVal.getLength());
        for (int m = 0; m < retVal.getLength(); ++m) {
            Node val = retVal.item(m);
            if (val.getNodeType() == Node.DOCUMENT_NODE) {
                val = ((Document) val).getDocumentElement();
            }
            result.add(val);
        }
    } else if (someRes instanceof String) {
        // Wrapping in a document
        Document document = DOMUtils.newDocument();
        Element wrapper = document.createElement("wrapper");
        Text text = document.createTextNode((String) someRes);
        wrapper.appendChild(text);
        document.appendChild(wrapper);
        result = Collections.singletonList(text);
    } else {
        result = null;
    }

    return result;
}

From source file:org.wso2.carbon.humantask.core.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *
 * @param node DOM Node/* w ww .j  a v a 2s  .co m*/
 * @return String
 */
public static String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}

From source file:oscar.oscarMessenger.docxfer.util.MsgCommxml.java

public static Element addNode(Node parentNode, String name, String value) {
    Element node = null;/* w  ww  . ja  va  2  s .c  o m*/

    if (parentNode.getNodeType() == Node.DOCUMENT_NODE) {
        node = ((Document) parentNode).createElement(name);
    } else {
        node = parentNode.getOwnerDocument().createElement(name);
    }

    if (value != null) {
        node.appendChild(node.getOwnerDocument().createTextNode(value));
    }

    return (Element) parentNode.appendChild(node);
}