/**
   * Utility method to group child nodes by their names.
   *
   * @param parent parent node.
   * @return Map from name to child nodes.
   */
  private static Map<String, List<Node>> getChildNodes(Node parent) {
    if (parent == null) return Collections.emptyMap();

    Map<String, List<Node>> children = new HashMap<String, List<Node>>();

    NodeList nodes = parent.getChildNodes();
    int nNodes = nodes.getLength();
    for (int i = 0; i < nNodes; i++) {
      Node node = nodes.item(i);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      String name = node.getNodeName();
      List<Node> namesakes = children.get(name);
      if (namesakes == null) {
        namesakes = new ArrayList<Node>();
        children.put(name, namesakes);
      }
      namesakes.add(node);
    }

    return children;
  }