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:de.betterform.xml.dom.DOMUtil.java

/**
 * returns the first child of the contextnode which has the specified tagname and namespace uri regardless of the
 * depth in the tree.//from w  ww .  j a v  a 2  s.com
 *
 * @param contextNode where to start the search
 * @param nsuri       the namespace uri
 * @param tag         the local name part of the wanted child
 * @return the first child found under the contextnode
 * todo: should return Element instead of Node
 */
public static Node getFirstChildByTagNameNS(Node contextNode, String nsuri, String tag) {
    Node n = null;

    if (contextNode.getNodeType() == Node.DOCUMENT_NODE) {
        n = ((Document) contextNode).getDocumentElement();

        if (!(n.getNamespaceURI().equals(nsuri) && n.getNodeName().equals(tag))) {
            n = null;
        }
    } else {
        NodeList nodes = ((Element) contextNode).getElementsByTagNameNS(nsuri, tag);

        if (nodes != null) {
            n = nodes.item(0);
        }
    }

    return n;
}

From source file:cc.siara.csv_ml.ParsedObject.java

/**
 * Traverse to parent element to go up one level
 *///from  w w w .  jav a2  s  .c  o  m
public void traverseToParent() {
    if (target == TARGET_W3C_DOC) {
        if (cur_element.getNodeType() != Node.DOCUMENT_NODE) {
            cur_element = cur_element.getParentNode();
        }
    } else {
        JSONObject parent_ref = (JSONObject) cur_jo.get("parent_ref");
        cur_jo = parent_ref;
    }
}

From source file:DOMProcessor.java

/** Searches the given node for a given attribute and returns the value associated with it.
  * This version does not recurse to children of the given node.
  * @param attributeName Attribute to search for.
  * @param node Node from which to start search.
  * @return Value associated with the attribute, or null if not found.  
  *//*  w  ww . jav a 2  s  .co  m*/
public String getNodeAttribute(String attributeName, Node node) {
    // Only consider document or element nodes.
    if ((node.getNodeType() != Node.DOCUMENT_NODE) && (node.getNodeType() != Node.ELEMENT_NODE)) {
        return null;
    }

    // Search attributes associated with the node.
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (attribute.getNodeName().equalsIgnoreCase(attributeName)) {
            return attribute.getNodeValue();
        }
    }

    // If we get this far, the attribute has not been found.
    return null;
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java

/**
 * <p>/*from  w ww . j  av a2 s  .co  m*/
 * Implementation of MathML unification. In the given W3C DOM represented
 * XML document find all maths nodes (see
 * {@link DocumentParser#findMathMLNodes(org.w3c.dom.Document)}) and
 * remember links to operator elements and other elements in
 * {@link #nodesByDepth} data structure. Then substitute them gradualy for
 * series of formulae with leaf elements substituted for a special
 * unification representing symbol {@code &#x25CD;} (for Presentation
 * MathML, see {@link Constants#PMATHML_UNIFICATOR}) or {@code &#x25D0;}
 * (for Content MathML, see {@link Constants#CMATHML_UNIFICATOR}).
 * </p>
 * <p>
 * Resulting series of the original and unified MathML nodes is itself
 * encapsulated in a new element &lt;unified-math&gt; (see
 * {@link Constants#UNIFIED_MATHML_ROOT_ELEM}) in XML namespace
 * <code>http://mir.fi.muni.cz/mathml-unification/</code> (see
 * {@link Constants#UNIFIED_MATHML_NS}) and put to the place of the original
 * math element {@link Node} in the XML DOM representation the node is
 * attached to.
 * </p>
 *
 * @param mathNode W3C DOM XML document representation attached MathML node
 * to work on.
 * @param workInPlace If <code>true</code>, given <code>mathNode</code> will
 * be modified in place; if <code>false</code>, <code>mathNode</code> will
 * not be modified and series of modified nodes will be returned.
 * @param operatorUnification If <code>true</code> unify also operator
 * nodes, otherwise keep operator nodes intact.
 * @return <code>null</code> if <code>workInPlace</code> is
 * <code>false</code>; otherwise collection of unified versions of the
 * <code>mathNode</code> with key of the {@link HashMap} describing order
 * (level of unification) of elements in the collection.
 */
private HashMap<Integer, Node> unifyMathMLNodeImpl(Node mathNode, boolean operatorUnification,
        boolean workInPlace) {

    if (mathNode.getOwnerDocument() == null) {
        String msg = "The given node is not attached to any document.";
        if (mathNode.getNodeType() == Node.DOCUMENT_NODE) {
            msg = "The given node is document itself. Call with mathNode.getDocumentElement() instead.";
        }
        throw new IllegalArgumentException(msg);
    }

    nodesByDepth = new HashMap<>();

    Node unifiedMathNode = null;
    HashMap<Integer, Node> unifiedNodesList = null;
    Document unifiedMathDoc = null;

    if (workInPlace) {
        // New element encapsulating the series of unified formulae.
        unifiedMathNode = mathNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                UNIFIED_MATHML_ROOT_ELEM);
        mathNode.getParentNode().replaceChild(unifiedMathNode, mathNode);
        unifiedMathNode.appendChild(mathNode.cloneNode(true));
    } else {
        unifiedNodesList = new HashMap<>();
        // Create a new separate DOM to work over with imporeted clone of the node given by user
        unifiedMathDoc = DOMBuilder.createNewDocWithNodeClone(mathNode, true);
        mathNode = unifiedMathDoc.getDocumentElement();
    }

    // Parse XML subtree starting at mathNode and remember elements by their depth.
    rememberLevelsOfNodes(mathNode, operatorUnification);

    // Build series of formulae of level by level unified MathML.
    NodeLevel<Integer, Integer> level = new NodeLevel<>(getMaxMajorNodesLevel(), NUMOFMINORLEVELS);
    int levelAttrCounter = 0;
    Collection<Attr> maxLevelAttrs = new LinkedList<>();
    while (level.major > 0) {
        if (nodesByDepth.containsKey(level)) {
            if (unifyAtLevel(level)) {
                levelAttrCounter++;

                Node thisLevelMathNode = mathNode.cloneNode(true);
                Attr thisLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_LEVEL_ATTR);
                Attr maxLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_MAX_LEVEL_ATTR);
                maxLevelAttrs.add(maxLevelAttr);

                thisLevelAttr.setTextContent(String.valueOf(levelAttrCounter));

                ((Element) thisLevelMathNode).setAttributeNodeNS(thisLevelAttr);
                ((Element) thisLevelMathNode).setAttributeNodeNS(maxLevelAttr);

                if (workInPlace) {
                    unifiedMathNode.appendChild(thisLevelMathNode);
                } else {
                    // Create a new document for every node in the collection.
                    unifiedNodesList.put(levelAttrCounter,
                            DOMBuilder.cloneNodeToNewDoc(thisLevelMathNode, true));
                }
            }
        }
        level.minor--;
        if (level.minor <= 0) {
            level.major--;
            level.minor = NUMOFMINORLEVELS;
        }
    }
    for (Attr attr : maxLevelAttrs) {
        attr.setTextContent(String.valueOf((levelAttrCounter)));
    }

    if (workInPlace) {
        return null;
    } else {
        for (Node node : unifiedNodesList.values()) {
            Attr maxLevelAttr = (Attr) node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_MAX_LEVEL_ATTR);
            if (maxLevelAttr != null) {
                maxLevelAttr.setTextContent(String.valueOf((levelAttrCounter)));
            }
        }
        return unifiedNodesList;
    }

}

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

/**
 * gets the first child of a node which is a text or cdata node.
 *///from  www.j  a  v  a  2  s  .  co  m
public static Node getTextNode(Node start) {
    Node n = null;

    start.normalize();

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

    int len = nl.getLength();

    if (len == 0) {
        return null;
    }

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

        if (n.getNodeType() == Node.TEXT_NODE) {
            return n;
        } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) {
            return n;
        }
    }

    return null;
}

From source file:tut.pori.javadocer.Javadocer.java

/**
 * converts the given node into an xml document and prints out that xml document
 * /*from   w  w w. ja va 2s  . c om*/
 * @param node
 * @return the given node as xml string
 */
private String toString(Node node) {
    StringWriter sw = new StringWriter();
    try {
        if (node.getNodeType() == Node.DOCUMENT_NODE) {
            cleanWhiteSpace((org.w3c.dom.Document) node);
        } else {
            cleanWhiteSpace(node.getOwnerDocument());
        }
        _transformer.transform(new DOMSource(node), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException ex) {
        LOGGER.error(ex, ex);
        throw new IllegalArgumentException("Invalid transformer settings.");
    }
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * returns true if current Node's modelitem is readonly or any of it's ancestors is readonly
 * @param n/*  ww w  .j a  v a  2 s . c  om*/
 * @return true if any of the ancestors or the node itself is readonly false otherwise
 */
private boolean isReadonly(Node n) {
    if (n.getNodeType() == Node.DOCUMENT_NODE)
        return false;
    if (getModelItem(n).isReadonly()) {
        return true;
    } else if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
        return isReadonly(((Attr) n).getOwnerElement());
    } else {
        return isReadonly(n.getParentNode());
    }
}

From source file:DOMProcessor.java

/** Returns a DOM element with the given name that is the child of the 
  * given node. This is a non-recursive method that only looks for immediate
  * children. Note that unlike <code>getNodeElements()</code> this method only
  * returns the first matched child of the given node.
  * @param name Element name to search for.
  * @param node Node from which to examine children.
  * @return Child node or null if none found.
  *//*from w  w w  .  j  a v  a 2s. co m*/
public Node getNodeElement(String name, Node node) {
    // Only consider document or element nodes.
    if ((node.getNodeType() != Node.DOCUMENT_NODE) && (node.getNodeType() != Node.ELEMENT_NODE)) {
        return null;
    }

    NodeList children = node.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);

        // Only consider element child nodes.
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            if (child.getNodeName().equalsIgnoreCase(name)) {
                return child;
            }
        }
    }

    // If we get this far, no child node was found.
    return null;
}

From source file:com.globalsight.everest.tda.TdaHelper.java

private void domNodeVisitor(Node p_node, ArrayList matchList, long tmProfileThreshold) {
    HashMap TDAResults = new HashMap();
    LeverageTDAResult tdaResult = null;/*w  w  w  .  j  av a2  s.  co  m*/

    if (matchList.size() > 0) {
        tdaResult = (LeverageTDAResult) matchList.get(matchList.size() - 1);
    }

    while (true) {
        if (p_node == null) {
            return;
        }

        switch (p_node.getNodeType()) {
        case Node.DOCUMENT_NODE:
            domNodeVisitor(p_node.getFirstChild(), matchList, tmProfileThreshold);
            return;
        case Node.ELEMENT_NODE:
            String nodeName = p_node.getNodeName().toLowerCase();

            if (nodeName.equals("alt-trans")) {
                String tuid = "-1";

                NamedNodeMap parentAttrs = p_node.getParentNode().getAttributes();

                for (int i = 0; i < parentAttrs.getLength(); ++i) {
                    Node att = parentAttrs.item(i);
                    String attname = att.getNodeName();
                    String value = att.getNodeValue();

                    if (attname.equals("id")) {
                        tuid = value;
                    }
                }

                NamedNodeMap attrs = p_node.getAttributes();
                boolean fromTDA = false;
                String percentValue = "";

                for (int i = 0; i < attrs.getLength(); ++i) {
                    Node att = attrs.item(i);
                    String attname = att.getNodeName();
                    String value = att.getNodeValue();

                    if (attname.equals("tda:provider")) {
                        fromTDA = true;
                    }

                    if (attname.equals("match-quality")) {
                        percentValue = value;
                    }

                }

                if (fromTDA) {
                    if (PecentToInt(percentValue) > tmProfileThreshold
                            || PecentToInt(percentValue) == tmProfileThreshold) {
                        tdaResult = new LeverageTDAResult();
                        tdaResult.setTuid(Long.parseLong(tuid));
                        tdaResult.setMatchPercent(percentValue);
                        matchList.add(tdaResult);
                    } else {
                        p_node = p_node.getNextSibling();
                        break;
                    }
                }
            }

            domNodeVisitor(p_node.getFirstChild(), matchList, tmProfileThreshold);
            p_node = p_node.getNextSibling();
            break;
        case Node.TEXT_NODE:
            nodeName = p_node.getNodeName().toLowerCase();

            if (p_node.getParentNode() != null && p_node.getParentNode().getParentNode() != null) {
                String parentNodeName = p_node.getParentNode().getNodeName().toLowerCase();
                String grandNodeName = p_node.getParentNode().getParentNode().getNodeName().toLowerCase();

                if (grandNodeName.equals("alt-trans") && parentNodeName.equals("target")) {
                    if (tdaResult != null) {
                        tdaResult.setResultText(p_node.getNodeValue());
                    }
                } else if (grandNodeName.equals("alt-trans") && parentNodeName.equals("source")) {
                    if (tdaResult != null) {
                        tdaResult.setSourceText(p_node.getNodeValue());
                    }
                }
            }

            p_node = p_node.getNextSibling();
            break;
        }
    }
}

From source file:com.intuit.karate.Script.java

public static void evalXmlEmbeddedExpressions(Node node, ScriptContext context) {
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        node = node.getFirstChild();//from  ww w  .  j  a  v a 2s . co m
    }
    NamedNodeMap attribs = node.getAttributes();
    int attribCount = attribs.getLength();
    for (int i = 0; i < attribCount; i++) {
        Attr attrib = (Attr) attribs.item(i);
        String value = attrib.getValue();
        value = StringUtils.trimToEmpty(value);
        if (isEmbeddedExpression(value)) {
            try {
                ScriptValue sv = evalInNashorn(value.substring(1), context);
                attrib.setValue(sv.getAsString());
            } catch (Exception e) {
                logger.warn("embedded xml-attribute script eval failed: {}", e.getMessage());
            }
        }
    }
    NodeList nodes = node.getChildNodes();
    int childCount = nodes.getLength();
    for (int i = 0; i < childCount; i++) {
        Node child = nodes.item(i);
        String value = child.getNodeValue();
        if (value != null) {
            value = StringUtils.trimToEmpty(value);
            if (isEmbeddedExpression(value)) {
                try {
                    ScriptValue sv = evalInNashorn(value.substring(1), context);
                    child.setNodeValue(sv.getAsString());
                } catch (Exception e) {
                    logger.warn("embedded xml-text script eval failed: {}", e.getMessage());
                }
            }
        } else if (child.hasChildNodes()) {
            evalXmlEmbeddedExpressions(child, context);
        }
    }
}