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:Main.java

/**
 * Generates XPath expression with the option of the Node values appended
 *
 * @param node             the Node whose XPath is to be found
 * @param ignoreWhitespace the flag to indicate if Whitespace will be ignored
 * @param includeValues    the flag to indicate if Node values will be included
 * @param noIndex          the flag to indicate if Node indexes are included
 * @return the XPath string representation of the Node
 *//*w w w.  j a  va  2s.c o m*/

public static String generateXPath(Node node, boolean ignoreWhitespace, boolean includeValues, boolean noIndex)

{

    boolean noValues = !includeValues;

    if (node == null)

        return "";

    Node parent = node.getParentNode();

    int index = noIndex ? 0 : getXPathNodeIndex(node, ignoreWhitespace);

    String indexStr = "";

    if (index > 0)

        indexStr = "[" + Integer.toString(index) + "]";

    //printNode(node);

    //printNode(parent);

    if (node.getNodeType() == Node.DOCUMENT_NODE)

    {

        // return only the blank String, since all the other types are preceded with /

        return "";

    } else if (node.getNodeType() == Node.TEXT_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr : "/TEXT(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ELEMENT_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                "/" + node.getNodeName() + indexStr;

    } else if (node.getNodeType() == Node.COMMENT_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr
                        : "/COMMENT(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ENTITY_REFERENCE_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr
                        : "/EntityReference(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr : "/PI(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE)

    {

        return generateXPath(((Attr) node).getOwnerElement(), ignoreWhitespace, noValues, noIndex) +

                "/'@" + node.getNodeName() +

                (noValues ? "" : "=" + node.getNodeValue()) + "]";

    } else if (node.getNodeType() == Node.DOCUMENT_TYPE_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() : "/DOCTYPE(" + node.getNodeName() + ")");

    } else if (node.getNodeType() == Node.CDATA_SECTION_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() : "/CDATA(" + node.getNodeName() + ")");

    }

    // Wont reach this far but just in case

    return "";

}

From source file:MainClass.java

private void dumpLoop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.CDATA_SECTION_NODE:
        System.out.println(indent + "CDATA_SECTION_NODE");
        break;//ww  w  .j  av a 2  s  .  c o  m
    case Node.COMMENT_NODE:
        System.out.println(indent + "COMMENT_NODE");
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        System.out.println(indent + "DOCUMENT_FRAGMENT_NODE");
        break;
    case Node.DOCUMENT_NODE:
        System.out.println(indent + "DOCUMENT_NODE");
        break;
    case Node.DOCUMENT_TYPE_NODE:
        System.out.println(indent + "DOCUMENT_TYPE_NODE");
        break;
    case Node.ELEMENT_NODE:
        System.out.println(indent + "ELEMENT_NODE");
        break;
    case Node.ENTITY_NODE:
        System.out.println(indent + "ENTITY_NODE");
        break;
    case Node.ENTITY_REFERENCE_NODE:
        System.out.println(indent + "ENTITY_REFERENCE_NODE");
        break;
    case Node.NOTATION_NODE:
        System.out.println(indent + "NOTATION_NODE");
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        System.out.println(indent + "PROCESSING_INSTRUCTION_NODE");
        break;
    case Node.TEXT_NODE:
        System.out.println(indent + "TEXT_NODE");
        break;
    default:
        System.out.println(indent + "Unknown node");
        break;
    }
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
        dumpLoop(list.item(i), indent + "   ");
}

From source file:Main.java

public static void getNodeData(Node node, StringBuffer buf) {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.DOCUMENT_NODE:
    case Node.ELEMENT_NODE: {
        for (Node child = node.getFirstChild(); null != child; child = child.getNextSibling()) {
            buf.append('<');
            buf.append(node.getNodeName());
            buf.append('>');
            getNodeData(child, buf);//from w  ww  .  ja va  2s  .co m
            buf.append("</");
            buf.append(node.getNodeName());
            buf.append('>');
        }
    }
        break;
    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE:
        buf.append(node.getNodeValue());
        break;
    case Node.ATTRIBUTE_NODE:
        buf.append(node.getNodeValue());
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
        break;
    default:
        // ignore
        break;
    }
}

From source file:de.betterform.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *//*from   w w w  .  j  a v  a  2 s .  co m*/
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation",
                    schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * __UNDOCUMENTED__//from w  ww . jav  a 2s.  co m
 *
 * @param start __UNDOCUMENTED__
 * @param name  __UNDOCUMENTED__
 * @return __UNDOCUMENTED__
 */
public static Element getChildElement(Node start, String name) {
    //        NodeList nl=start.getChildNodes();
    NodeList nl = null;

    if (start.getNodeType() == Node.DOCUMENT_NODE) {
        nl = ((Document) start).getDocumentElement().getChildNodes();
    } else {
        nl = start.getChildNodes();
    }

    int len = nl.getLength();
    Node n = null;

    for (int i = 0; i < len; i++) {
        n = nl.item(i);

        if (n.getNodeType() == Node.ELEMENT_NODE) {
            if (n.getNodeName().equals(name)) {
                return (Element) n;
            }
        }
    }

    return null;
}

From source file:DOMDump.java

private void dumpLoop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.CDATA_SECTION_NODE:
        System.out.println(indent + "CDATA_SECTION_NODE");
        break;// w  w w  .j  a v  a2s . c  o  m
    case Node.COMMENT_NODE:
        System.out.println(indent + "COMMENT_NODE");
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        System.out.println(indent + "DOCUMENT_FRAGMENT_NODE");
        break;
    case Node.DOCUMENT_NODE:
        System.out.println(indent + "DOCUMENT_NODE");
        break;
    case Node.DOCUMENT_TYPE_NODE:
        System.out.println(indent + "DOCUMENT_TYPE_NODE");
        break;
    case Node.ELEMENT_NODE:
        System.out.println(indent + "ELEMENT_NODE");
        break;
    case Node.ENTITY_NODE:
        System.out.println(indent + "ENTITY_NODE");
        break;
    case Node.ENTITY_REFERENCE_NODE:
        System.out.println(indent + "ENTITY_REFERENCE_NODE");
        break;
    case Node.NOTATION_NODE:
        System.out.println(indent + "NOTATION_NODE");
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        System.out.println(indent + "PROCESSING_INSTRUCTION_NODE");
        break;
    case Node.TEXT_NODE:
        System.out.println(indent + "TEXT_NODE");
        break;
    default:
        System.out.println(indent + "Unknown node");
        break;
    }

    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
        dumpLoop(list.item(i), indent + "   ");

}

From source file:Main.java

public static Element createElement(Node node, String name, String value, Map<String, Object> attributes) {
    Document doc = node.getNodeType() == Node.DOCUMENT_NODE ? (Document) node : node.getOwnerDocument();
    Element element = doc.createElement(name);
    element.setTextContent(value);/*w w  w  .  jav  a 2  s.c  o m*/
    addAttributes(element, attributes);
    return element;
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.XmlUtils.java

public static String getXmlDataSubstituteNode(Node node, String substituteWith, String substituteInWhat) {
    StringBuilder sb = new StringBuilder();
    switch (node.getNodeType()) {
    case Node.COMMENT_NODE:
    case Node.ENTITY_NODE:
    case Node.ENTITY_REFERENCE_NODE:
    case Node.NOTATION_NODE:
    case Node.PROCESSING_INSTRUCTION_NODE:
        break;/*from   www.  j ava 2s  .  c o m*/
    case Node.DOCUMENT_NODE:
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.ELEMENT_NODE: {
        String nodeName = node.getNodeName();
        if (!substituteInWhat.equals(nodeName)) {
            sb.append("<").append(nodeName);
            StringBuilder attrs = new StringBuilder();
            StringBuilder children = new StringBuilder();
            NamedNodeMap nnm = node.getAttributes();
            if (nnm != null) {
                for (int i = 0; i < nnm.getLength(); i++) {
                    Node attr = nnm.item(i);
                    attrs.append(" ").append(getXmlDataSubstituteNode(attr, substituteWith, substituteInWhat));
                }
            }
            NodeList nl = node.getChildNodes();
            if (nl != null) {
                for (int i = 0; i < nl.getLength(); i++) {
                    Node child = nl.item(i);
                    if (child.getNodeType() == Node.ATTRIBUTE_NODE) {
                        attrs.append(" ")
                                .append(getXmlDataSubstituteNode(child, substituteWith, substituteInWhat));
                    } else {
                        children.append(getXmlDataSubstituteNode(child, substituteWith, substituteInWhat));
                    }
                }
            }
            sb.append(attrs.toString());
            if (children.length() > 0) {
                sb.append(">").append(children.toString()).append("</").append(nodeName).append(">");
            } else {
                sb.append("/>");
            }
        } else {
            sb.append(substituteWith);
        }
        break;
    }
    case Node.ATTRIBUTE_NODE: {
        sb.append(node.getNodeName()).append("=\"").append(StringEscapeUtils.escapeXml(node.getNodeValue()))
                .append("\"");
        break;
    }
    case Node.CDATA_SECTION_NODE: {
        sb.append("<![CDATA[").append(StringEscapeUtils.escapeXml(node.getNodeValue())).append("]]>");
    }
    case Node.TEXT_NODE: {
        sb.append(StringEscapeUtils.escapeXml(node.getNodeValue()));
    }
    }
    return sb.toString();
}

From source file:Main.java

public final static Class<? extends Node> toClass(final short nodeType) {
    switch (nodeType) {
    case Node.ATTRIBUTE_NODE:
        return Attr.class;
    case Node.CDATA_SECTION_NODE:
        return CDATASection.class;
    case Node.COMMENT_NODE:
        return Comment.class;
    case Node.DOCUMENT_FRAGMENT_NODE:
        return DocumentFragment.class;
    case Node.DOCUMENT_NODE:
        return Document.class;
    case Node.DOCUMENT_TYPE_NODE:
        return DocumentType.class;
    case Node.ELEMENT_NODE:
        return Element.class;
    case Node.ENTITY_NODE:
        return Entity.class;
    case Node.ENTITY_REFERENCE_NODE:
        return EntityReference.class;
    case Node.NOTATION_NODE:
        return Notation.class;
    case Node.PROCESSING_INSTRUCTION_NODE:
        return ProcessingInstruction.class;
    case Node.TEXT_NODE:
        return Text.class;
    }// ww  w.j a v  a 2 s.c  o m
    throw new RuntimeException("Unrecognized node type " + nodeType);
}

From source file:Main.java

private static void renderNode(StringBuffer sb, Node node) {
    if (node == null) {
        sb.append("null");
        return;/*w w  w.  j  a  v  a 2s.c o m*/
    }
    switch (node.getNodeType()) {

    case Node.DOCUMENT_NODE:
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        Node root = ((Document) node).getDocumentElement();
        renderNode(sb, root);
        break;

    case Node.ELEMENT_NODE:
        String name = getNodeNameWithNamespace(node);
        NamedNodeMap attributes = node.getAttributes();
        if (attributes.getLength() == 0) {
            sb.append("<" + name + ">");
        } else {
            sb.append("<" + name + " ");
            int attrlen = attributes.getLength();
            for (int i = 0; i < attrlen; i++) {
                Node attr = attributes.item(i);
                String attrName = getNodeNameWithNamespace(attr);
                sb.append(attrName + "=\"" + escapeChars(attr.getNodeValue()));
                if (i < attrlen - 1)
                    sb.append("\" ");
                else
                    sb.append("\">");
            }
        }
        NodeList children = node.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                renderNode(sb, children.item(i));
            }
        }
        sb.append("</" + name + ">");
        break;

    case Node.TEXT_NODE:
        sb.append(escapeChars(node.getNodeValue()));
        break;

    case Node.CDATA_SECTION_NODE:
        sb.append("<![CDATA[" + node.getNodeValue() + "]]>");
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        sb.append("<?" + node.getNodeName() + " " + escapeChars(node.getNodeValue()) + "?>");
        break;

    case Node.ENTITY_REFERENCE_NODE:
        sb.append("&" + node.getNodeName() + ";");
        break;

    case Node.DOCUMENT_TYPE_NODE:
        // Ignore document type nodes
        break;

    case Node.COMMENT_NODE:
        sb.append("<!--" + node.getNodeValue() + "-->");
        break;
    }
    return;
}