generic foreach iteration of NamedNodeMap

You can create your own Iterable wrapper for NamedNodeMap and then use it in a foreach loop.

For example, this could be a simple implementation:

public final class NamedNodeMapIterable implements Iterable<Node> {

    private final NamedNodeMap namedNodeMap;

    private NamedNodeMapIterable(NamedNodeMap namedNodeMap) {
        this.namedNodeMap = namedNodeMap;
    }

    public static NamedNodeMapIterable of(NamedNodeMap namedNodeMap) {
        return new NamedNodeMapIterable(namedNodeMap);
    }

    private class NamedNodeMapIterator implements Iterator<Node> {

        private int nextIndex = 0;

        @Override
        public boolean hasNext() {
            return (namedNodeMap.getLength() > nextIndex);
        }
        @Override
        public Node next() {
            Node item = namedNodeMap.item(nextIndex);
            nextIndex = nextIndex + 1;
            return item;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

    }

    @Override
    public Iterator<Node> iterator() {
        return new NamedNodeMapIterator();
    }
}

In this case, this would be the usage:

private void iterate(NamedNodeMap attributesList) {
    for (Node node : NamedNodeMapIterable.of(attributesList)) {
        System.out.println("Attribute: "
                + node.getNodeName() + " = " + node.getNodeValue());
    }
}

With a similar approach you could create an Iterable over Map.Entry<String, String> instances.


I don't think there is a nicer way to use those APIs. (Update: OK - maybe https://stackoverflow.com/a/28626556/139985 counts as nice.)

Bear in mind that the W3C DOM Java APIs were specified before Java had generics or the new for syntax, or even the Iterator interface. Also bear in mind that the W3C DOM APIs for Java are actually the result of mapping an IDL specification to Java.

If you want nicer APIs for manipulating XML, etc in memory, maybe you should look at JDOM.


As you can't cast NamedNodeMap to a Map, I suggest to loop using a classic for loop like that :

int numAttrs = namedNodeMap.getLength();
System.out.println("Attributes:");
for (int i = 0; i < numAttrs; i++){
   Attr attr = (Attr) pParameterNode.getAttributes().item(i);
   String attrName = attr.getNodeName();
   String attrValue = attr.getNodeValue();
   System.out.println("\t[" + attrName + "]=" + attrValue);
}