Example usage for org.w3c.dom Node hasAttributes

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

Introduction

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

Prototype

public boolean hasAttributes();

Source Link

Document

Returns whether this node (if it is an element) has any attributes.

Usage

From source file:Main.java

private static String logXMLSubNode(Node node, int deepth) {

    int i;//from   w  w w  . ja v a2  s . c  o  m
    String nodeStr = new String();
    String interStr = new String();
    for (i = 0; i < deepth; i++)
        interStr += "\t";

    nodeStr += interStr + "<" + node.getNodeName() + internal;
    if (node.hasAttributes()) {
        NamedNodeMap attrs = node.getAttributes();

        // add the attrubite name-value pairs
        for (i = 0; i < attrs.getLength(); i++) {
            Node a = attrs.item(i);
            nodeStr += a.getNodeName() + "=" + a.getNodeValue() + internal;
        }
    }
    if (node.hasChildNodes()) {
        nodeStr += ">\n";
        NodeList ns = node.getChildNodes();
        for (i = 0; i < ns.getLength(); i++) {
            nodeStr += logXMLSubNode(ns.item(i), deepth + 1);
        }
        nodeStr += interStr + "</" + node.getNodeName() + ">\n";
    } else {
        if (node.getNodeValue() != null) {
            nodeStr += ">" + node.getNodeValue() + "<" + node.getNodeName();
        }
        nodeStr += "/>\n";
    }
    return nodeStr;
}

From source file:com.ewcms.common.io.HtmlStringUtil.java

public static String getPureText(Node node) {
    if (!node.hasChildNodes() && isTextNode(node))
        return node.getNodeValue();
    if (isFiltered(node))
        return "";
    if (node.hasAttributes()) {
        Node a = node.getAttributes().getNamedItem("style");
        if (a != null) {
            String style = a.getNodeValue();
            Pattern p = Pattern.compile("display\\s*\\:\\s*none", 2);
            if (p.matcher(style).find())
                return "";
        }//  w ww. j  a  va2s  . co  m
    }
    StringBuffer sb = new StringBuffer();
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        Node child = list.item(i);
        String name = child.getNodeName();
        sb.append(getPureText(child));
        sb.append(" ");
        if (name.equals("TR") || name.equals("P") || name.equals("DIV"))
            sb.append("\n");
    }

    return sb.toString();
}

From source file:Main.java

public static Object toObject(Node node) {
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        node = node.getFirstChild();//from w w w .j av  a2 s  .  c o  m
        Map<String, Object> map = new LinkedHashMap<>(1);
        map.put(node.getNodeName(), toObject(node));
        return map;
    }
    Object value = getElementValue(node);
    if (node.hasAttributes()) {
        Map<String, Object> wrapper = new LinkedHashMap<>(2);
        wrapper.put("_", value);
        wrapper.put("@", getAttributes(node));
        return wrapper;
    } else {
        return value;
    }
}

From source file:Main.java

private static void printNote(NodeList nodeList) {

    for (int count = 0; count < nodeList.getLength(); count++) {

        Node tempNode = nodeList.item(count);

        // make sure it's element node.
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

            // get node name and value
            System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
            System.out.println("Node Value =" + tempNode.getTextContent());

            if (tempNode.hasAttributes()) {

                // get attributes names and values
                NamedNodeMap nodeMap = tempNode.getAttributes();

                for (int i = 0; i < nodeMap.getLength(); i++) {

                    Node node = nodeMap.item(i);
                    System.out.println("attr name : " + node.getNodeName());
                    System.out.println("attr value : " + node.getNodeValue());

                }/* w w w  .  jav  a 2s  . c o  m*/

            }

            if (tempNode.hasChildNodes()) {

                // loop again if has child nodes
                printNote(tempNode.getChildNodes());

            }

            System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");

        }

    }

}

From source file:MainClass.java

static void listNodes(Node node, String indent) {
    String nodeName = node.getNodeName();
    System.out.println(indent + " Node: " + nodeName);
    short type = node.getNodeType();
    System.out.println(indent + " Node Type: " + nodeType(type));
    if (type == TEXT_NODE) {
        System.out.println(indent + " Content is: " + ((Text) node).getWholeText());
    } else if (node.hasAttributes()) {
        System.out.println(indent + " Element Attributes are:");
        NamedNodeMap attrs = node.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Attr attribute = (Attr) attrs.item(i);
            System.out.println(indent + " " + attribute.getName() + " = " + attribute.getValue());
        }// ww  w .j  av  a 2s  .c o  m
    }

    NodeList list = node.getChildNodes();
    if (list.getLength() > 0) {
        System.out.println(indent + " Child Nodes of " + nodeName + " are:");
        for (int i = 0; i < list.getLength(); i++) {
            listNodes(list.item(i), indent + "  ");
        }
    }
}

From source file:Main.java

public static Element findElement(Node sourceElm, String attrName, String sAttrValue) {
    if (sourceElm.hasChildNodes()) {
        NodeList nodes = sourceElm.getChildNodes();

        for (int i = 0; i < nodes.getLength(); i++) {
            if (Node.ELEMENT_NODE == nodes.item(i).getNodeType()) {
                Element elm = findElement(nodes.item(i), attrName, sAttrValue);

                if (((Element) elm).getAttribute(attrName).equals(sAttrValue)) {
                    return (Element) elm;
                }// ww w . j av  a 2s.  co  m
            }
        }
    } else {
        if (sourceElm.hasAttributes() && ((Element) sourceElm).getAttribute(attrName).equals(sAttrValue)) {
            return (Element) sourceElm;
        }
    }

    return (Element) sourceElm;
}

From source file:Main.java

private static void traverseNode(Node parentNode, JsonObject parentJson, JsonObject upperJson) {
    NodeList childList = parentNode.getChildNodes();
    for (int i = 0; i < childList.getLength(); i++) {
        JsonObject childJson = new JsonObject();
        Node childNode = childList.item(i);

        if (childNode.getNodeType() == Node.TEXT_NODE) {
            if (childNode.getNodeValue().trim().length() != 0) {
                // non empty text node reached, so add to the parent
                processTextNode(parentNode, upperJson, childJson, childNode);
            }/*from  w  w w.j  a  va2s .  co  m*/
        } else if (childNode.getNodeType() == Node.ELEMENT_NODE) {

            if (childNode.hasAttributes()) {
                // attributes exist, so go thru them
                traverseAttributes(childJson, childNode);
            }

            if (childNode.hasChildNodes()) {
                // child nodes exist, so go into them
                traverseNode(childNode, childJson, parentJson);
            }

            if (childNode.getNodeType() != Node.TEXT_NODE) {
                // non text node element
                if (ADDED_BY_VALUE.contains(childNode)) {
                    // already added as a value
                    if (parentJson.has(childNode.getNodeName())) {
                        // there is already such an element as expected
                        JsonElement existing = parentJson.get(childNode.getNodeName());
                        if (existing instanceof JsonPrimitive) {
                            // it is a primitive as expected
                            Iterator attrs = childJson.entrySet().iterator();
                            if (attrs.hasNext()) {
                                // there are attributes, so reorganize the element to include the attributes and the
                                // value as property - #text
                                reorganizeForAttributes(parentJson, childNode, existing, attrs);
                            }
                        } else if (existing instanceof JsonArray) {
                            // already added and reorganized as an array, so take the last element of this type and
                            // add the attributes
                            Iterator attrs = childJson.entrySet().iterator();
                            if (attrs.hasNext()) {
                                reorganizeAddAttributes(childNode, attrs);
                            }
                        } else if (existing instanceof JsonObject) {
                            System.err.println("ERROR: found object, but expected primitive or array");
                        }
                    } else {
                        System.err.println("ERROR: expected element, but it does not exist");
                    }
                    // remove it from the list
                    ADDED_BY_VALUE.remove(childNode);
                } else {
                    if (parentJson.has(childNode.getNodeName())) {
                        // parent already has such an element
                        JsonElement existing = parentJson.get(childNode.getNodeName());
                        if (existing instanceof JsonArray) {
                            // and it is already an array, so just add the child to the array
                            ((JsonArray) existing).add(childJson);
                        } else if (existing instanceof JsonObject) {
                            // and it not an array, so reorganize the element
                            reorganizeElement(parentNode, parentJson, childJson, childNode, existing);
                        }
                    } else {
                        // no such an element yet, so add it to the parent
                        parentJson.add(childNode.getNodeName(), childJson);
                    }
                }
            }
        } else if (childNode.getNodeType() == Node.CDATA_SECTION_NODE) {
            // processTextNode(parentNode, upperJson, childJson, childNode);
            String base64 = Base64.getEncoder().encodeToString(childNode.getNodeValue().getBytes());
            parentJson.addProperty(childNode.getNodeName(), base64);
        } else {
            System.err.println("ERROR: unsupported node type: " + childNode.getNodeType());
        }
    }
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Obtain the STIX version from the Content_Binding urn
 *
 * @param node Content_Binding node/*from w ww .  j a va 2s  .  c om*/
 * @return a String containing the STIX version
 * @throws DOMException DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation
 * is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
 * <a href="https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/DOMException.html">Reference to Oracle Documentation.</a>
 *
 */
private static String getStixVersion(Node node) throws DOMException {
    try {
        String urnStr = "";
        if (node.hasAttributes()) {
            Attr attr = (Attr) node.getAttributes().getNamedItem("binding_id");
            if (attr != null) {
                urnStr = attr.getValue();
            }
        }
        if (urnStr.isEmpty()) {
            urnStr = node.getTextContent();
        }
        if (urnStr != null && !urnStr.isEmpty()) {
            int lastIndex = urnStr.lastIndexOf(":");
            String version = "";
            if (lastIndex >= 0) {
                version = urnStr.substring(lastIndex + 1);
            }
            return version;
        }
    } catch (DOMException e) {
        logger.debug("DOMException when attempting to parse binding id from a STIX node. ");
        throw e;
    }
    return "";
}

From source file:Main.java

public static String getXPath(Node node) {
    if (null == node)
        return null;

    // declarations
    Node parent = null;// ww w  .  j a v  a 2 s  .c  om
    Stack<Node> hierarchy = new Stack<Node>();
    StringBuilder buffer = new StringBuilder();

    // push element on stack
    hierarchy.push(node);

    parent = node.getParentNode();
    while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) {
        // push on stack
        hierarchy.push(parent);

        // get parent of parent
        parent = parent.getParentNode();
    }

    // construct xpath
    Object obj = null;
    while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) {
        Node n = (Node) obj;
        boolean handled = false;

        // only consider elements
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) n;

            // is this the root element?
            if (buffer.length() == 0) {
                // root element - simply append element name
                buffer.append(n.getNodeName());
            } else {
                // child element - append slash and element name
                buffer.append("/");
                buffer.append(n.getNodeName());

                if (n.hasAttributes()) {
                    // see if the element has a name or id attribute
                    if (e.hasAttribute("id")) {
                        // id attribute found - use that
                        buffer.append("[@id='" + e.getAttribute("id") + "']");
                        handled = true;
                    } else if (e.hasAttribute("name")) {
                        // name attribute found - use that
                        buffer.append("[@name='" + e.getAttribute("name") + "']");
                        handled = true;
                    }
                }

                if (!handled) {
                    // no known attribute we could use - get sibling index
                    int prev_siblings = 1;
                    Node prev_sibling = n.getPreviousSibling();
                    while (null != prev_sibling) {
                        if (prev_sibling.getNodeType() == n.getNodeType()) {
                            if (prev_sibling.getNodeName().equalsIgnoreCase(n.getNodeName())) {
                                prev_siblings++;
                            }
                        }
                        prev_sibling = prev_sibling.getPreviousSibling();
                    }
                    buffer.append("[" + prev_siblings + "]");
                }
            }
        }
    }

    // return buffer
    return buffer.toString();
}

From source file:com.mirth.connect.donkey.server.data.jdbc.XmlQuerySource.java

public void load(String xmlFile) throws XmlQuerySourceException {
    Document document = null;//  w w w  .  j  a v  a2s.  c  o m

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
        InputStream is = ResourceUtil.getResourceStream(XmlQuerySource.class, xmlFile);
        document = documentBuilder.parse(is);
        IOUtils.closeQuietly(is);
    } catch (Exception e) {
        throw new XmlQuerySourceException("Failed to read query file: " + xmlFile, e);
    }

    NodeList queryNodes = document.getElementsByTagName("query");
    int queryNodeCount = queryNodes.getLength();

    for (int i = 0; i < queryNodeCount; i++) {
        Node node = queryNodes.item(i);

        if (node.hasAttributes()) {
            Attr attr = (Attr) node.getAttributes().getNamedItem("id");

            if (attr != null) {
                String query = StringUtils.trim(node.getTextContent());

                if (query.length() > 0) {
                    queries.put(attr.getValue(), query);
                }
            }
        }
    }
}