我想用Java保存XML格式。
XML应如下所示:
<person>
<id>101</id>
<name>test name</name>
</person>
<person>
<id>202</id>
<name>another name</name>
</person>
<company>
<bureau1>
<id>101</id>
<id>202</id>
</bureau1>
<bureau2>
<id>202</id>
</bureau2>
<company>
如何使用JAXB来做到这一点。如果我尝试过,我会让公司参与,但是 我无法导出Person-Data。我正在寻找解决方案的日子。
是的,这是类和XML的示例。但是给人的信息在哪里?
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Company {
private String companyNo;
private String name;
@XmlElementWrapper(name="employee")
@XmlElement(name="person")
@XmlIDREF
private List<Person> employee;
}
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
@XmlID
private String pId;
private String name;
}
public class CompanyExport {
public static void main(String[] args) throws FileNotFoundException, IOException {
List<Person> employee = new ArrayList<Person>();
Person p1 = new Person();
p1.setName("Name1");
p1.setPId("p101");
employee.add(p1);
Person p2 = new Person();
p2.setName("Name2");
p2.setPId("p202");
employee.add(p2);
Person p3 = new Person();
p3.setName("Name3");
p3.setPId("p303");
employee.add(p3);
Company c = new Company();
c.setEmployee(employee);
c.setCompanyNo("c101");
c.setName("JAXB Company1");
try (FileOutputStream ausgabe = new FileOutputStream(new File("CompanyExport.xml"))){
JAXBContext context = JAXBContext.newInstance(Company.class);
Marshaller jMarshall = context.createMarshaller();
jMarshall.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jMarshall.marshal(c, ausgabe);
System.out.println("DONE!");
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//} catch (SAXException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<company>
<companyNo>c101</companyNo>
<name>JAXB Company1</name>
<employee>
<person>p101</person>
<person>p202</person>
<person>p303</person>
</employee>
</company>