Example usage for org.w3c.dom Node getChildNodes

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

Introduction

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

Prototype

public NodeList getChildNodes();

Source Link

Document

A NodeList that contains all children of this node.

Usage

From source file:Main.java

/**
 * Extracts child elements from node whith type <code>ELEMENT_NODE</code>.
 *
 * @param node root node of XML document for search.
 * @return iterator with proper node childs.
 *///from w ww. j  av a2  s.  c o m
public static Iterator<Element> getChildElements(final Node node) {
    //        node.normalize();
    return new Iterator<Element>() {
        private final NodeList nodes = node.getChildNodes();
        private int nextPos = 0;
        private Element nextElement = seekNext();

        public boolean hasNext() {
            return nextElement != null;
        }

        public Element next() {
            if (nextElement == null)
                throw new NoSuchElementException();
            final Element result = nextElement;
            nextElement = seekNext();
            return result;
        }

        public void remove() {
            throw new UnsupportedOperationException("operation not supported");
        }

        private Element seekNext() {
            for (int i = nextPos, len = nodes.getLength(); i < len; i++) {
                final Node childNode = nodes.item(i);
                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    nextPos = i + 1;
                    return (Element) childNode;
                }
            }
            return null;
        }
    };
}

From source file:Main.java

private static void findAllElementsByAttribute(Node node, String tagName, String attrName, String attrValue,
        List<Element> result) {
    if (node == null) {
        return;/*  w  w w.jav a 2s.  c om*/
    }
    NodeList nodeList = node.getChildNodes();
    if (nodeList == null) {
        return;
    }
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node currNode = nodeList.item(i);
        Element element = checkIfElement(currNode, tagName);
        if (element != null && element.getAttribute(attrName).equals(attrValue)) {
            result.add(element);
            continue;
        }
        findAllElementsByAttribute(currNode, tagName, attrName, attrValue, result);
    }
}

From source file:edu.gslis.ts.ChunkToFile.java

public static Map<Integer, FeatureVector> readEvents(String path, Stopper stopper) {
    Map<Integer, FeatureVector> queries = new TreeMap<Integer, FeatureVector>();

    try {//from  www . j  a  v  a2  s  . com
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(new File(path));

        NodeList events = doc.getDocumentElement().getElementsByTagName("event");
        for (int i = 0; i < events.getLength(); i++) {
            Node event = events.item(i);
            NodeList elements = event.getChildNodes();
            int id = -1;
            String query = "";

            for (int j = 0; j < elements.getLength(); j++) {
                Node element = elements.item(j);
                if (element == null)
                    continue;

                if (element.getNodeName().equals("id"))
                    id = Integer.parseInt(element.getTextContent());
                else if (element.getNodeName().equals("query"))
                    query = element.getTextContent();
            }
            queries.put(id, new FeatureVector(query, stopper));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return queries;
}

From source file:Main.java

/**
 * @param parentNode// ww  w  .  java 2s .  co m
 *            is the element tag that contains all the AttirbuteValuePair
 *            tags as children
 * @return Map Returns the AV pairs in a Map where each entry in the Map is
 *         an AV pair. The key is the attribute name and the value is a Set
 *         of String objects.
 */
public static Map parseAttributeValuePairTags(Node parentNode) {

    NodeList avList = parentNode.getChildNodes();
    Map map = null;
    final int numAVPairs = avList.getLength();
    if (numAVPairs <= 0) {
        return EMPTY_MAP;
    }
    for (int l = 0; l < numAVPairs; l++) {
        Node avPair = avList.item(l);
        if ((avPair.getNodeType() != Node.ELEMENT_NODE) || !avPair.getNodeName().equals("AttributeValuePair")) {
            continue;
        }
        NodeList leafNodeList = avPair.getChildNodes();
        long numLeafNodes = leafNodeList.getLength();
        if (numLeafNodes < 2) {
            // TODO: More error handling required later for missing
            // 'Attribute' or
            // 'Value' tags.
            continue;
        }
        String key = null;
        Set values = null;
        // Since Attribute tag is always the first leaf node as per the
        // DTD,and
        // values can one or more, Attribute tag can be parsed first and
        // then
        // iterate over the values, if any.
        Node attributeNode = null;
        for (int i = 0; i < numLeafNodes; i++) {
            attributeNode = leafNodeList.item(i);
            if ((attributeNode.getNodeType() == Node.ELEMENT_NODE)
                    && (attributeNode.getNodeName().equals("Attribute"))) {
                i = (int) numLeafNodes;
            } else {
                continue;
            }
        }
        key = ((Element) attributeNode).getAttribute("name");
        // Now parse the Value tags. If there are not 'Value' tags, ignore
        // this key
        // TODO: More error handling required later for zero 'Value' tags.
        for (int m = 0; m < numLeafNodes; m++) {
            Node valueNode = leafNodeList.item(m);
            if ((valueNode.getNodeType() != Node.ELEMENT_NODE) || !valueNode.getNodeName().equals("Value")) {
                // TODO: Error handling required here
                continue;
            }
            if (values == null) {
                values = new HashSet();
            }
            Node fchild = (Text) valueNode.getFirstChild();
            if (fchild != null) {
                String value = fchild.getNodeValue();
                if (value != null) {
                    values.add(value.trim());
                }
            }
        }
        if (values == null) {
            // No 'Value' tags found. So ignore this key.
            // TODO: More error handling required later for zero
            // 'Value'tags.
            continue;
        }
        if (map == null) {
            map = new HashMap();
        }
        Set oldValues = (Set) map.get(key);
        if (oldValues != null)
            values.addAll(oldValues);
        map.put(key, values);

        // now reset values to prepare for the next AV pair.
        values = null;
    }
    if (map == null) {
        return EMPTY_MAP;
    } else {
        return map;
    }

}

From source file:Main.java

public static Node findNode(Node node, String nodeName) {
    if (node == null) {
        return null;
    }// www  .  j a  va  2  s. c  o m

    if (node.getNodeName().equals(nodeName)) {
        return node;
    }
    NodeList nodeList = node.getChildNodes();
    int i = 0;
    for (int cnt = nodeList.getLength(); i < cnt; i++) {
        Node child = findNode(nodeList.item(i), nodeName);
        if (child != null) {
            return child;
        }
    }
    return null;
}

From source file:cz.muni.fi.webmias.TeXConverter.java

/**
 * Converts TeX formula to MathML using LaTeXML through a web service.
 *
 * @param query String containing one or more keywords and TeX formulae
 * (formulae enclosed in $ or $$)./* ww w.j  a v  a2  s  .  c  o  m*/
 * @return String containing formulae converted to MathML that replaced
 * original TeX forms. Non math tokens are connected at the end.
 */
public static String convertTexLatexML(String query) {
    query = query.replaceAll("\\$\\$", "\\$");
    if (query.matches(".*\\$.+\\$.*")) {
        try {
            HttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(LATEX_TO_XHTML_CONVERSION_WS_URL);

            // Request parameters and other properties.
            List<NameValuePair> params = new ArrayList<>(1);
            params.add(new BasicNameValuePair("code", query));
            httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // Execute and get the response.
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    try (InputStream responseContents = resEntity.getContent()) {
                        DocumentBuilder dBuilder = MIaSUtils.prepareDocumentBuilder();
                        org.w3c.dom.Document doc = dBuilder.parse(responseContents);
                        NodeList ps = doc.getElementsByTagName("p");
                        String convertedMath = "";
                        for (int k = 0; k < ps.getLength(); k++) {
                            Node p = ps.item(k);
                            NodeList pContents = p.getChildNodes();
                            for (int j = 0; j < pContents.getLength(); j++) {
                                Node pContent = pContents.item(j);
                                if (pContent instanceof Text) {
                                    convertedMath += pContent.getNodeValue() + "\n";
                                } else {
                                    TransformerFactory transFactory = TransformerFactory.newInstance();
                                    Transformer transformer = transFactory.newTransformer();
                                    StringWriter buffer = new StringWriter();
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.transform(new DOMSource(pContent), new StreamResult(buffer));
                                    convertedMath += buffer.toString() + "\n";
                                }
                            }
                        }
                        return convertedMath;
                    }
                }
            }

        } catch (TransformerException | SAXException | ParserConfigurationException | IOException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return query;
}

From source file:Main.java

private static void findAllElementsByAttributes(Node node, String tagName, String attrName,
        List<String> attrValues, List<Element> result) {
    if (node == null) {
        return;// w  ww  .  j a  v a  2 s.c  o  m
    }
    NodeList nodeList = node.getChildNodes();
    if (nodeList == null) {
        return;
    }
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node currNode = nodeList.item(i);
        Element element = checkIfElement(currNode, tagName);
        if (element != null) {
            for (String value : attrValues) {
                if (element.getAttribute(attrName).equals(value)) {
                    result.add(element);
                    break;
                }
            }
        }
        findAllElementsByAttributes(currNode, tagName, attrName, attrValues, result);
    }
}

From source file:Main.java

static public Node removeChild(Node xmlNode, String name, boolean ignoreCase) {
    Node removedChild = null;/*from  ww  w  .j  a  v  a  2s.c o m*/

    String key = name;
    if (ignoreCase)
        key = key.toLowerCase();

    NodeList childNodes = xmlNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        String childName = child.getNodeName();
        if (ignoreCase)
            childName = childName.toLowerCase();

        if (childName.equals(key)) {
            removedChild = child;
            xmlNode.removeChild(child);
            break;
        }
    }
    return removedChild;
}

From source file:Main.java

/**
 *
 * @param xmlContent//w  w  w.  jav  a2s  .co m
 * @param charset
 * @param expression
 * @return
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 */
public static List<String> getValues(String xmlContent, Charset charset, String expression)
        throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {

    List<String> valueList = new ArrayList<String>();

    NodeList nodeList = getNodeList(xmlContent, expression);
    int length = nodeList.getLength();
    for (int seq = 0; seq < length; seq++) {
        Node node = nodeList.item(seq);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            NodeList childNodeList = node.getChildNodes();
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < childNodeList.getLength(); i++) {
                Node childNode = childNodeList.item(i);
                if (childNode.getNodeType() == Node.TEXT_NODE) {
                    sBuilder.append(((Text) childNode).getNodeValue());
                }
            }
            valueList.add(sBuilder.toString());

        } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            valueList.add(node.getNodeValue());
        }
    }

    return valueList;
}

From source file:Main.java

/**
 * Recursively fetches all nodes of specified ns. For multi ns documents
 *
 * @param node the starting node.// w  ww .  j  av  a 2 s. c  om
 * @param namespace desired ns
 */
private static List<Node> getAllNodesByNamespaceRecursive(Node node, String namespace) {
    List nsNodeList = new ArrayList();
    if (node.getNamespaceURI() != null && node.getNamespaceURI().equals(namespace)) {
        nsNodeList.add(node);
    }
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); ++i) {
        nsNodeList.addAll(getAllNodesByNamespaceRecursive(list.item(i), namespace));
    }
    return nsNodeList;
}