How do I read all childrem of Item element and store the in an object
This is my sample xml file
<People>
<Person>
<Name>Ben</Name>
<Items>
<Item>Pen</Item>
<Item>Paper</Item>
<Item>Books</Item>
</Items>
</Person>
<Person>
<Name>Alex</Name>
<Items>
<Item>Pencil</Item>
<Item>Eraser</Item>
</Items>
</People>
I made a Person object with getters and setters
public class Person{ // SAMPLE OBJECT
private String name; @getters and setters
private String item; @getters and setters
}
This is my method where it read
public ArrayList<Person> getPeople(){
people = new ArrayList<>();
Person a = null;
if (Files.exists(peoplePath)) // prevent the FileNotFoundException
{
// create the XMLInputFactory object
XMLInputFactory inputFactory = XMLInputFactory.newFactory();
try
{
// create a XMLStreamReader object
FileReader fileReader =
new FileReader(peoplePath.toFile());
XMLStreamReader reader =
inputFactory.createXMLStreamReader(fileReader);
// read from the file
while (reader.hasNext())
{
int eventType = reader.getEventType();
switch (eventType)
{
case XMLStreamConstants.START_ELEMENT:
String elementName = reader.getLocalName();
if (elementName.equals("Person"))
{
a = new Person();
}
if (elementName.equals("Name"))
{
String name = reader.getElementText();
a.setName(name);
}
if (elementName.equals("Item"))
{
String item= reader.getElementText();
a.setItem(item);
}
break;
case XMLStreamConstants.END_ELEMENT:
elementName = reader.getLocalName();
if (elementName.equals("Person"))
{
people.add(a);
}
break;
default:
break;
}
reader.next();
}
}
catch (IOException | XMLStreamException e)
{
System.out.println(e);
return null;
}
}
return people;
}
This method displays
Ben
Alex
but if I get the items it only using similar code, it displays
Books
Eraser
public static void displayPeople(){
ArrayList<Person> people = personDAO.getPeople();
People p = null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < people.size(); i++)
{
a = people.get(i);
sb.append(a.getName());
sb.append("\n");
}
System.out.println(sb.toString());
}
I wanted to do this output
Ben
Pen
Paper
Book
Alex
Pencil
Eraser
First, your xml is missing the Person element closing just before the end.
</Person>
Second, your Person class is not really correct. Items should be a list of String instead of just a String.
public class Person {
// private keyword is removed for brevity
String name;
List<String> items = new ArrayList<>();
}
Third, your code needs to be updated to use the list of items as follows:
if (elementName.equals("Item"))
{
String item= reader.getElementText();
a.getItems().add(item);
}
I'm actually wondering: Why do you choose Stax instead of JAXB? Your XML schema is actually quite straight-forward to be handled with JAXB. And there will be very little boilerplate code for the conversion of XML to Java object, which means your code will be more readable and maintainable with JAXB. Just my 2 cents.