简体   繁体   English

使用 STAX JAVA 在 XML 中读取 Element 的多个子项

[英]Read multiple child of Element in XML using STAX JAVA

How do I read all childrem of Item element and store the in an object如何读取 Item 元素的所有子项并将其存储在 object 中

This is my sample xml file这是我的示例 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>

I made a Person object with getters and setters我用 getter 和 setter 做了一个人 object

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我想做这个 output

Ben
    Pen
    Paper
    Book
Alex
    Pencil 
    Eraser

First, your xml is missing the Person element closing just before the end.首先,您的 xml 缺少在结束前关闭的 Person 元素。

</Person>

Second, your Person class is not really correct.其次,您的 Person class 并不正确。 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?我其实在想:为什么选择Stax而不是JAXB? Your XML schema is actually quite straight-forward to be handled with JAXB.您的 XML 架构实际上非常简单,可以使用 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. 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.只是我的2美分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM