[英]Read multiple child of Element in XML using STAX JAVA
如何讀取 Item 元素的所有子項並將其存儲在 object 中
這是我的示例 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>
我用 getter 和 setter 做了一個人 object
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;
}
該方法顯示
本
亞歷克斯
但如果我只使用類似的代碼獲取項目,它會顯示
圖書
橡皮
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());
}
我想做這個 output
Ben
Pen
Paper
Book
Alex
Pencil
Eraser
首先,您的 xml 缺少在結束前關閉的 Person 元素。
</Person>
其次,您的 Person class 並不正確。 項目應該是一個字符串列表,而不僅僅是一個字符串。
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);
}
我其實在想:為什么選擇Stax而不是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. 只是我的2美分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.