无法使用JAXB从XML文件读取

时间:2015-01-19 03:33:27

标签: java xml jaxb

我正在尝试阅读下面的XML文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parts>
    <item>CPU</item>
    <item>GPU</item>
    <item>PSU</item>
</parts>

我的目标是将项添加到DefaultDataModel,以便我可以更新JList。但是,当我到达每个循环时,没有任何内容添加到列表中,也没有任何内容打印到控制台。有人可以告诉我,如果我做错了吗?

public void load()
{
    // First clear the JLit before loading anything
    partList.clear();
    chosenList.clear();

    File file = new File("partsList.xml");

    try
    {
        // Setup JAXB to create a list of strings from the XML file
        JAXBContext context = JAXBContext.newInstance(Parts.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        // Read the XML file
        List<String> parts = (List<String>) unmarshaller.unmarshal(file);
        System.out.println(parts);

        for (String item : parts)
        {
            chosenList.addElement(item);
            System.out.println(item);
        }

        list_1.setModel(chosenList);
        list_1.repaint();
    }

    catch (JAXBException e)
    {
        e.printStackTrace();            
    }       
}

Parts.java

@XmlRootElement
public class Parts extends AbstractList<String>
{
    /* This allows me to have a single instantiation of this class for
     * adding the PC components before writing them to the XML file
     */

    @XmlElement(name="item")
    private List<String> list = new ArrayList<String>();

    @Override
    public boolean add(String element)
    {
        return list.add(element);
    }

    @Override
    public String get(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return 0;
    }
}

1 个答案:

答案 0 :(得分:2)

首先,您的Parts类不完整。应该实现get和size方法。

@Override
public String get(int arg0) {
    return list.get(arg0);
}

@Override
public int size() {
    return list.size();
}

然后,解组为您提供了一个Parts对象,而不是一个字符串列表。所以,应该是:

Parts parts = (Parts) unmarshaller.unmarshal(file);
System.out.println(parts);

for (int i = 0; i < parts.size(); i++) {
    chosenList.addElement(parts.get(i));
    System.out.println(parts.get(i));
}