我有这样的XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data-set>
<record>
<TARIH>data</TARIH>
<GUNLER>data</GUNLER>
<YEMEK1>data</YEMEK1>
<YEMEK2>data</YEMEK2>
</record>
<record>
<TARIH>data</TARIH>
<GUNLER>data</GUNLER>
<YEMEK1>data</YEMEK1>
<YEMEK2>data</YEMEK2>
</record>
</data-set>
我想用Java中的JAXB解析它。这是我的DataSet类。
@XmlRootElement(name="data-set")
@XmlAccessorType(XmlAccessType.FIELD)
public class DataSet {
@XmlElement(name="record")
private List<Record> records = null;
public List<Record> getRecords(){
return records;
}
public void setRecords(List<Record> records){
this.records = records;
}
}
这是我的记录课。
@XmlRootElement(name="record")
@XmlAccessorType(XmlAccessType.FIELD)
public class Record {
String TARIH,GUNLER,YEMEK1,ANAYEMEK1,ANAYEMEK2,YEMEK3,YEMEK4,SALATBAR1,SALATBAR2,SALATBAR3,SALATBAR4,SALATBAR5;
//getters and setters//
我尝试这样的事情。
public class Main {
public static void main(String[] args) throws JAXBException {
File file = new File("C:/Users/EMRE/Desktop/YEMEKHANE DATABASE/morning.xml");
JAXBContext jaxbcontext = JAXBContext.newInstance(Record.class);
Unmarshaller jaxbunmarshaller = jaxbcontext.createUnmarshaller();
Record record = (Record)jaxbunmarshaller.unmarshal(file);
System.out.println(record.getTARIH());
}
}
我遇到这样的错误。
Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"data-set"). Expected elements are <{}record>
我怎样才能解决这个问题?谢谢。
最佳答案
使用DataSet
类创建上下文。
JAXBContext jaxbcontext = JAXBContext.newInstance(DataSet.class);
也许您还需要添加
Record
(不确定):@XmlSeeAlso({Record.class})
public class DataSet {...}
但是我认为即使没有它也可能会起作用。
或者,您可以执行以下操作:
JAXBContext jaxbcontext = JAXBContext.newInstance(DataSet.class, Record.class);
还有其他一些基于软件包名称的context path替代方案。如果您手动编写类,不是那么简单。