Search code examples
javaxmliteratorjdom-2

Iterator only gets first Element in JavaFX


i am wondering why my Iterator only gets the first Element while getting trough a List from an XML reader

My XML File:

<Genre>
    <Name>Horror</Name>
    <Name>Action</Name>
    <Name>Kinderfilm</Name>
    <Name>Komödie</Name>
    <Name>Splatter</Name>
 </Genre>

My Java-Code:

List list = rootNode.getChildren("Genre");

System.out.println("Count Genre: " + list.size());
Iterator i = list.iterator();

while (i.hasNext()) {
   Element gen = (Element) i.next();
   String name = gen.getChildText("Name");
   System.out.println("NAME: " + name);
   genre.add(name);
}

It only gets one Element (Horror)

Hope someone can help me. Punching


Solution

  • Assuming that rootNode is the root of your document, then

    List list = rootNode.getChildren("Genre");
    

    will return a list with size 1 containg the Genre node.

    Iterating this list will of course only once run through the while body, with gen pointing to the Genre element.
    Calling gen.getChildText("Name") on this node will return the text content of the first child element named Name, returning Horror.

    What you probably want to do:

    Element genre = rootNode.getChild("Genre");
    
    Iterator<Element> names = genre.getChildren("Name").iterator();
    while (names.hasNext()) {
         String name = names.next().getText();
         ...
    }