Прочтите несколько дочерних элементов Element в XML, используя STAX JAVA - PullRequest
0 голосов
/ 02 августа 2020

Как мне прочитать все дочерние элементы элемента Item и сохранить их в объекте

Это мой образец xml файл

<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>

Я создал объект Person с помощью геттеров и сеттеров

public class Person{ // SAMPLE OBJECT
    private String name; @getters and setters 
    private String item; @getters and setters
}

Это мой метод, где он читает

  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;
    }


Этот метод отображает
Ben
Alex

, но если я получаю предметы, это только используя аналогичный код, он отображает
Книги
Ластик

    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());
    }

Я хотел сделать этот вывод

Ben
    Pen
    Paper
    Book
Alex
    Pencil 
    Eraser

1 Ответ

0 голосов
/ 02 августа 2020

Во-первых, в вашем xml отсутствует закрывающийся перед концом элемент Person.

</Person>

Во-вторых, ваш класс Person неверен. Элементы должны быть списком String, а не просто String.

public class Person {
// private keyword is removed for brevity
    String name; 
    List<String> items = new ArrayList<>(); 
}

В-третьих, ваш код необходимо обновить, чтобы использовать список элементов следующим образом:

if (elementName.equals("Item"))
{
    String item= reader.getElementText();
    a.getItems().add(item);
}

I ' Мне действительно интересно: почему вы выбрали Stax вместо JAXB? Ваша схема XML на самом деле довольно проста для обработки с помощью JAXB. И будет очень мало шаблонного кода для преобразования объекта XML в Java, что означает, что ваш код будет более читабельным и поддерживаемым с помощью JAXB. Всего мои 2 цента.

...