将XML解析/反序列化为JavaObjects [英] Parsing/Deserialize XML to JavaObjects
问题描述
我开始了一个新的小项目,我想从XML反序列化对象.
i started a small new project and i want to deserialize objects from XML.
我创建了一个xsd:
和示例XML文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hdb>
<country code="DE">
<variableHoliday daysAfterEaster="49" name="PENTECOAST" />
<fixedHoliday month="JANUARY" day="1" name="NEWYEAR" />
<region code="sa">
<fixedHoliday month="APRIL" day="1" name="FUNNYDAY" />
<variableHoliday daysAfterEaster="0" name="EASTERSUNDAY" />
</region>
<region code="ba">
<variableHoliday daysAfterEaster="12" name="CORPUSCHRISTI" />
</region>
</country>
<country code="US">
<fixedHoliday month="JULY" day="4" name="INDEPENDENCEDAY" />
</country>
<country code="AL">
<fixedHoliday month="JULY" day="4" name="INDEPENDENCEDAY" />
</country>
</hdb>
应该使用xsd等.
那么我如何才能将这些XML反序列化为一个不错的Java对象结构?
So how can i achive the deserialization of these XML to a nice Java-Object Structure?
像:
class HDB {
private HashMap<CountryCode,Country> map;
}
class Country {
private List<Holiday> list; // or two Lists with <variableHoliday> and <fixedHoliday>
private List<Region> regions;
}
class Region{
private List<Holiday> list; // or two Lists with <variableHoliday> and <fixedHoliday>
}
class variableHoliday {
private String name;
private int daysAfterEaster;
}
class fixedHoliday {
private String name;
private int day;
private MonthName month; // while MonthName is an enum defined like the enum from XSD
}
有什么想法可以轻松实现吗?
Any ideas how to achive that easy?
我想到jaxb尝试了一些东西,但是在我看来(对于jaxb来说是一个初学者),由于映射的原因,很难达到这种XML结构,就像这样写 v.
I thought of jaxb an tried some stuff, but it seems to me (im a beginner with jaxb) that its hard to achive this XML structure because of maps cant be written like v.
推荐答案
使用
xjc your_xsd_name -p packagename
为了生成Pojos,xjc是jdk附带的xml java编译器.
to generate Pojos, xjc is xml java compiler that comes with jdk.
一旦生成您的类,请按照以下步骤使用jaxb
once your classes are generated use jaxb as follows
JAXB编组
HDB hdb = new HDB();
JAXBContext jaxbContext = JAXBContext.newInstance(HDB.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.marshal(hdb, file);
jaxbMarshaller.marshal(hdb, System.out);
JAXB解组
File file = new File("your xml file");
JAXBContext jaxbContext = JAXBContext.newInstance(hdb.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
HDB hdb = (HDB) jaxbUnmarshaller.unmarshal(file);
System.out.println(hdb);
访问以下链接以获取更多信息 JAXB编组和解组
Visit following link for more info JAXB marshalling and unmarshalling
这篇关于将XML解析/反序列化为JavaObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!