Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:com.itelis.worker.dev.template.service.JRXmlDataSource.java

/**
 * Return the text that a node contains. This routine:
 * <ul>/*w w  w. j a  v a  2s  . c  o m*/
 * <li>Ignores comments and processing instructions.
 * <li>Concatenates TEXT nodes, CDATA nodes, and the results of recursively processing EntityRef nodes.
 * <li>Ignores any element nodes in the sublist. (Other possible options are to recurse into element sublists or throw an exception.)
 * </ul>
 * @param node a DOM node
 * @return a String representing node contents or null
 */
public String getText(Node node) {
    if (!node.hasChildNodes())
        return node.getNodeValue();

    StringBuffer result = new StringBuffer();

    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        Node subnode = list.item(i);
        if (subnode.getNodeType() == Node.TEXT_NODE) {
            String value = subnode.getNodeValue();
            if (value != null)
                result.append(value);
        } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) {
            String value = subnode.getNodeValue();
            if (value != null)
                result.append(value);
        } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
            // Recurse into the subtree for text
            // (and ignore comments)
            String value = getText(subnode);
            if (value != null)
                result.append(value);
        }
    }

    return result.toString();
}

From source file:com.apatar.buzzsaw.BuzzsawNode.java

private void addDinamicFieldToList(Node node) {
    String fieldNameSpace = node.getNamespaceURI();
    String fieldName = node.getLocalName();

    // does node have children or not
    if (node.hasChildNodes()) {
        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            if (1 == node.getChildNodes().item(i).getNodeType()) {
                addDinamicFieldToList(node.getChildNodes().item(i));
            }/*from w  w  w .  j  av a 2  s  .  c om*/
        }
    }

    // is this bazzsaw property or not
    if ("http://www.buzzsaw.com/projectpoint".equalsIgnoreCase(fieldNameSpace)) {
        fieldName = "Buzzsaw_" + fieldName;
    }

    // does dinamicFields have fieldName or not
    if (!dinamicFields.contains(fieldName)) {
        dinamicFields.add(fieldName);
    }
}

From source file:Main.java

protected static void print(PrintStream out, Node node) {
    if (node == null)
        return;//from   w  w  w .  java2  s .  c  o  m
    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        // out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        NodeList nodelist = node.getChildNodes();
        int size = nodelist.getLength();
        for (int i = 0; i < size; i++)
            print(out, nodelist.item(i));
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType docType = (DocumentType) node;
        out.print("<!DOCTYPE " + getDocumentTypeData(docType) + ">\n");
        break;
    }

    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {
            int size = map.getLength();
            for (int i = 0; i < size; i++) {
                Attr attr = (Attr) map.item(i);
                out.print(' ');
                out.print(attr.getNodeName());
                out.print("=\"");
                out.print(normalize(attr.getNodeValue()));
                out.print('"');
            }
        }

        if (!node.hasChildNodes())
            out.print("/>");
        else {
            out.print('>');
            NodeList nodelist = node.getChildNodes();
            int numChildren = nodelist.getLength();
            for (int i = 0; i < numChildren; i++)
                print(out, nodelist.item(i));

            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        NodeList nodelist = node.getChildNodes();
        if (nodelist != null) {
            int size = nodelist.getLength();
            for (int i = 0; i < size; i++)
                print(out, nodelist.item(i));

        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String s = node.getNodeValue();
        if (s != null && s.length() > 0) {
            out.print(' ');
            out.print(s);
        }
        out.print("?>");
        break;
    }

    case Node.COMMENT_NODE: {
        out.print("<!--");
        out.print(node.getNodeValue());
        out.print("-->");
        break;
    }

    default: {
        out.print(normalize(node.getNodeValue()));
        break;
    }
    }
    out.flush();
}

From source file:me.willowcheng.makerthings.model.OpenHABWidget.java

public OpenHABWidget(OpenHABWidget parent, Node startNode) {
    this.parent = parent;
    this.children = new ArrayList<OpenHABWidget>();
    this.mappings = new ArrayList<OpenHABWidgetMapping>();
    if (startNode.hasChildNodes()) {
        NodeList childNodes = startNode.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeName().equals("item")) {
                this.setItem(new OpenHABItem(childNode));
            } else if (childNode.getNodeName().equals("linkedPage")) {
                this.setLinkedPage(new OpenHABLinkedPage(childNode));
            } else if (childNode.getNodeName().equals("widget")) {
                new OpenHABWidget(this, childNode);
            } else {
                if (childNode.getNodeName().equals("type")) {
                    this.setType(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("widgetId")) {
                    this.setId(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("label")) {
                    this.setLabel(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("icon")) {
                    this.setIcon(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("url")) {
                    this.setUrl(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("minValue")) {
                    setMinValue(Float.valueOf(childNode.getTextContent()).floatValue());
                } else if (childNode.getNodeName().equals("maxValue")) {
                    setMaxValue(Float.valueOf(childNode.getTextContent()).floatValue());
                } else if (childNode.getNodeName().equals("step")) {
                    setStep(Float.valueOf(childNode.getTextContent()).floatValue());
                } else if (childNode.getNodeName().equals("refresh")) {
                    setRefresh(Integer.valueOf(childNode.getTextContent()).intValue());
                } else if (childNode.getNodeName().equals("period")) {
                    setPeriod(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("service")) {
                    setService(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("height")) {
                    setHeight(Integer.valueOf(childNode.getTextContent()));
                } else if (childNode.getNodeName().equals("mapping")) {
                    NodeList mappingChildNodes = childNode.getChildNodes();
                    String mappingCommand = "";
                    String mappingLabel = "";
                    for (int k = 0; k < mappingChildNodes.getLength(); k++) {
                        if (mappingChildNodes.item(k).getNodeName().equals("command"))
                            mappingCommand = mappingChildNodes.item(k).getTextContent();
                        if (mappingChildNodes.item(k).getNodeName().equals("label"))
                            mappingLabel = mappingChildNodes.item(k).getTextContent();
                    }//from w  ww  . jav  a2  s.co  m
                    OpenHABWidgetMapping mapping = new OpenHABWidgetMapping(mappingCommand, mappingLabel);
                    mappings.add(mapping);
                } else if (childNode.getNodeName().equals("iconcolor")) {
                    setIconColor(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("labelcolor")) {
                    setLabelColor(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("valuecolor")) {
                    setValueColor(childNode.getTextContent());
                } else if (childNode.getNodeName().equals("encoding")) {
                    setEncoding(childNode.getTextContent());
                }
            }
        }
    }
    this.parent.addChildWidget(this);
}

From source file:ali.arshad.soomro.aonawaredistservicesdk.AonawareDictServiceUtils.java

private AonawareDictServiceWordInfo parseWordInfo(Context context, Document docSource) {
    AonawareDictServiceWordInfo dictServiceWordInfo = new AonawareDictServiceWordInfo();

    try {/*from  w  w  w .  j  a  v a  2 s.c  om*/
        Node wordNode = docSource.getElementsByTagName("Word").item(0);
        Node definationNode = docSource.getElementsByTagName("Definition").item(0);
        String word = getNodeText(wordNode);
        String dictId = getNodeText(docSource.getElementsByTagName("Id").item(0));
        String dictName = getNodeText(docSource.getElementsByTagName("Name").item(0));
        String wordDefination = getNodeText(docSource.getElementsByTagName("WordDefinition").item(1));

        if (!definationNode.hasChildNodes()) {
            dictServiceWordInfo.setWord(getNodeText(wordNode));
            dictServiceWordInfo.setDictId(NOT_FOUND);
            dictServiceWordInfo.setDictName(NOT_FOUND);
            dictServiceWordInfo.setWordDefination(NOT_FOUND);
            return dictServiceWordInfo;
        } else {
            dictServiceWordInfo.setWord(word);
            dictServiceWordInfo.setDictId(dictId);
            dictServiceWordInfo.setDictName(dictName);
            dictServiceWordInfo.setWordDefination(wordDefination);
            return dictServiceWordInfo;
        }
    } catch (NullPointerException e) {
        dictServiceWordInfo.setWord(NOT_FOUND);
        dictServiceWordInfo.setDictId(NOT_FOUND);
        dictServiceWordInfo.setDictName(NOT_FOUND);
        dictServiceWordInfo.setWordDefination(NOT_FOUND);
        return dictServiceWordInfo;
    } catch (NoSuchMethodException e) {
        dictServiceWordInfo.setWord(NOT_FOUND);
        dictServiceWordInfo.setDictId(NOT_FOUND);
        dictServiceWordInfo.setDictName(NOT_FOUND);
        dictServiceWordInfo.setWordDefination(NOT_FOUND);
        return dictServiceWordInfo;
    }
}

From source file:com.apatar.buzzsaw.BuzzsawNode.java

private void putPropertyValueToTable(Node node, KeyInsensitiveMap datas) {
    String fieldNameSpace = node.getNamespaceURI();
    String fieldName = node.getLocalName();
    String fieldValue = node.getTextContent();

    // does node have children or not
    if (node.hasChildNodes()) {
        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            if (1 == node.getChildNodes().item(i).getNodeType()) {
                putPropertyValueToTable(node.getChildNodes().item(i), datas);
            }// w ww  . j  a  v a 2  s  . c o m
        }
    }

    // is this bazzsaw property or not
    if ("http://www.buzzsaw.com/projectpoint".equalsIgnoreCase(fieldNameSpace)) {
        fieldName = "Buzzsaw_" + fieldName;
    }

    List<Record> recs = getTiForConnection(OUT_CONN_POINT_NAME).getRecords();
    Record rec = Record.getRecordByFieldName(recs, fieldName);
    if (rec != null) {
        datas.put(fieldName, new JdbcObject(fieldValue, rec.getSqlType()));
    }
}

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();/*  ww w . ja v  a  2  s. 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);
        }
    }
}

From source file:Main.java

public static void assertEquivalent(Node node, Node node2) {
    if (node == null) {
        throw new IllegalArgumentException("the first node to be compared is null");
    }//from w w w  . j a  v a2 s .com

    if (node2 == null) {
        throw new IllegalArgumentException("the second node to be compared is null");
    }

    if (!node.getNodeName().equals(node2.getNodeName())) {
        throw new IllegalArgumentException("nodes have different node names");
    }

    int attrCount = 0;
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
        attrCount = attrs.getLength();
    }

    int attrCount2 = 0;
    NamedNodeMap attrs2 = node2.getAttributes();
    if (attrs2 != null) {
        attrCount2 = attrs2.getLength();
    }

    if (attrCount != attrCount2) {
        throw new IllegalArgumentException("nodes hava a different number of attributes");
    }

    outer: for (int i = 0; i < attrCount; i++) {
        Node n = attrs.item(i);
        String name = n.getNodeName();
        String value = n.getNodeValue();

        for (int j = 0; j < attrCount; j++) {
            Node n2 = attrs2.item(j);
            String name2 = n2.getNodeName();
            String value2 = n2.getNodeValue();

            if (name.equals(name2) && value.equals(value2)) {
                continue outer;
            }
        }
        throw new IllegalArgumentException("attribute " + name + "=" + value + " doesn't match");
    }

    boolean hasChildren = node.hasChildNodes();

    if (hasChildren != node2.hasChildNodes()) {
        throw new IllegalArgumentException("one node has children and the other doesn't");
    }

    if (hasChildren) {
        NodeList nl = node.getChildNodes();
        NodeList nl2 = node2.getChildNodes();

        short[] toFilter = new short[] { Node.TEXT_NODE, Node.ATTRIBUTE_NODE, Node.COMMENT_NODE };
        List nodes = filter(nl, toFilter);
        List nodes2 = filter(nl2, toFilter);

        int length = nodes.size();

        if (length != nodes2.size()) {
            throw new IllegalArgumentException("nodes hava a different number of children");
        }

        for (int i = 0; i < length; i++) {
            Node n = (Node) nodes.get(i);
            Node n2 = (Node) nodes2.get(i);
            assertEquivalent(n, n2);
        }
    }
}

From source file:org.dasein.cloud.aws.platform.SimpleDB.java

@Override
public Iterable<KeyValuePair> getKeyValuePairs(String inDomainId, String itemId, boolean consistentRead)
        throws CloudException, InternalException {
    APITrace.begin(provider, "KVDB.getKeyValuePairs");
    try {//from  w  ww  .  jav a 2  s  .  c  om
        Map<String, String> parameters = provider.getStandardSimpleDBParameters(provider.getContext(),
                GET_ATTRIBUTES);
        EC2Method method;
        Document doc;

        parameters.put("DomainName", inDomainId);
        parameters.put("ItemName", itemId);
        parameters.put("ConsistentRead", String.valueOf(consistentRead));
        method = new EC2Method(SERVICE_ID, provider, parameters);
        try {
            doc = method.invoke();
        } catch (EC2Exception e) {
            String code = e.getCode();

            if (code != null && code.equals("NoSuchDomain")) {
                return null;
            }
            throw new CloudException(e);
        }
        ;
        ArrayList<KeyValuePair> pairs = new ArrayList<KeyValuePair>();

        NodeList blocks = doc.getElementsByTagName("Attribute");
        for (int i = 0; i < blocks.getLength(); i++) {
            Node node = blocks.item(i);

            if (node.hasChildNodes()) {
                NodeList children = node.getChildNodes();
                String key = null, value = null;

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

                    if (item.hasChildNodes()) {
                        String nv = item.getFirstChild().getNodeValue();

                        if (item.getNodeName().equals("Name")) {
                            key = nv;
                        } else if (item.getNodeName().equals("Value")) {
                            value = nv;
                        }
                    }
                }
                if (key != null) {
                    pairs.add(new KeyValuePair(key, value));
                }
            }
        }
        return pairs;
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.platform.SimpleDB.java

@Override
public Iterable<ResourceStatus> listKeyValueDatabaseStatus() throws CloudException, InternalException {
    APITrace.begin(provider, "KVDB.listKeyValueDatabaseStatus");
    try {/*from w w w  .j a  v a  2s  .c  om*/
        ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>();
        String marker = null;

        do {
            Map<String, String> parameters = provider.getStandardSimpleDBParameters(provider.getContext(),
                    LIST_DOMAINS);
            EC2Method method;
            NodeList blocks;
            Document doc;

            if (marker != null) {
                parameters.put("NextToken", marker);
            }
            method = new EC2Method(SERVICE_ID, provider, parameters);
            try {
                doc = method.invoke();
            } catch (EC2Exception e) {
                throw new CloudException(e);
            }
            marker = null;
            blocks = doc.getElementsByTagName("NextToken");
            if (blocks.getLength() > 0) {
                for (int i = 0; i < blocks.getLength(); i++) {
                    Node item = blocks.item(i);

                    if (item.hasChildNodes()) {
                        marker = item.getFirstChild().getNodeValue().trim();
                    }
                }
                if (marker != null) {
                    break;
                }
            }
            blocks = doc.getElementsByTagName("DomainName");
            for (int i = 0; i < blocks.getLength(); i++) {
                Node name = blocks.item(i);

                if (name.hasChildNodes()) {
                    list.add(new ResourceStatus(name.getFirstChild().getNodeValue(), true));
                }
            }
        } while (marker != null);
        return list;
    } finally {
        APITrace.end();
    }
}