Can I iterate through a NodeList using for-each in Java?

前端 未结 10 1105
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 00:55

I want to iterate through a NodeList using a for-each loop in Java. I have it working with a for loop and a do-while loop but not for-each.

Node         


        
10条回答
  •  执笔经年
    2020-12-09 01:21

    The validated solution is very useful, but here I share an improved solution based on the valid one, this helps you iterate as well, but easy to use, and secure:

    public class XMLHelper {
        private XMLHelper() { }
    
        public static List getChildNodes(NodeList l) {
            List children = Collections.emptyList();
            if (l != null && l.getLength() > 0) {
                if (l.item(0) != null && l.item(0).hasChildNodes()) {
                    children = new NodeListWrapper(l.item(0).getChildNodes());
                }
            }
            return children;
        }
    
        public static List getChildNodes(Node n) {
            List children = Collections.emptyList();
            if (n != null && n.hasChildNodes()) {
                NodeList l = n.getChildNodes();
                if (l != null && l.getLength() > 0) {
                    children = new NodeListWrapper(l);
                }
            }
            return children;
        }
    
        private static final class NodeListWrapper extends AbstractList implements RandomAccess {
            private final NodeList list;
            NodeListWrapper(NodeList l) {
                list = l;
            }
            public Node get(int index) {
                return list.item(index);
            }
            public int size() {
                return list.getLength();
            }
        }
    

    }

    Usage:

     for (Node inner : XMLHelper.getChildNodes(node)) { ... }
    

    Thanks @Holger.

提交回复
热议问题