0

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

wero
  • 32,544
  • 3
  • 59
  • 84
Punching
  • 55
  • 7

1 Answers1

2

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();
     ...
}
wero
  • 32,544
  • 3
  • 59
  • 84
  • I assume you meant to write `getChildren("Name")` instead of getChildren("name") and `getText()` instead of getText("Name")? – VGR Jan 14 '16 at 19:22
  • Thanks, this was the solution, (s.time i feel so f**** stupid) – Punching Jan 14 '16 at 19:24