Example #1
0
  /**
   * Search specific element by key and tagName.
   *
   * @param root root element
   * @param key search keyword
   * @param tagName search tag name
   * @return search result, null of either input is invalid or the looking result is not found.
   */
  private Element searchForKey(final Element root, final String key, final String tagName) {
    if (root == null || StringUtils.isEmptyString(key)) {
      return null;
    }
    final Queue<Element> queue = new LinkedList<>();
    queue.offer(root);

    while (!queue.isEmpty()) {
      final Element pe = queue.poll();
      final NodeList pchildrenList = pe.getChildNodes();
      for (int i = 0; i < pchildrenList.getLength(); i++) {
        final Node node = pchildrenList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
          queue.offer((Element) node);
        }
      }
      String value = pe.getNodeName();
      if (StringUtils.isEmptyString(value) || !value.equals(tagName)) {
        continue;
      }

      value = pe.getAttribute(ATTRIBUTE_NAME_NAME);
      if (StringUtils.isEmptyString(value)) {
        continue;
      }

      if (value.equals(key)) {
        return pe;
      }
    }
    return null;
  }