Java 使用JAXB从具有多个类的xml创建对象?
我有xsd和xml文件。首先,我从xsd文件生成了Java类,这一部分已经完成,现在我必须使用xml将数据输入到对象中?我正在使用下面的代码,但这是抛出JAXBEExceptionJava 使用JAXB从具有多个类的xml创建对象?,java,xml,jaxb,Java,Xml,Jaxb,我有xsd和xml文件。首先,我从xsd文件生成了Java类,这一部分已经完成,现在我必须使用xml将数据输入到对象中?我正在使用下面的代码,但这是抛出JAXBEException try { File file = new File("D:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.generated"); Unmarshaller jaxbUnmarsh
try {
File file = new File("D:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.generated");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employee empObj = (Employee) jaxbUnmarshaller.unmarshal(file);
System.out.println(empObj.getName());
} catch (JAXBException e) {
e.printStackTrace();
}
这是我的xml文件,它包含两个类:
约翰
5000
史密斯
有人能帮我吗?重要的 您的代码中有一个错误。您跳过了此步骤:
JAXBElement element = (JAXBElement) jaxbUnmarshaller.unmarshal(f);
嗯,我很久以前就与JAXB合作过 然而,在这种情况下,我们习惯于定义一个顶级元素(在Java代码或xsd文件中)来封装其他元素 例如:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<People>
<Employee>
<name>John</name>
<salary>5000</salary>
</Employee>
<Customer>
<name>Smith</name>
</Customer>
</People>
您可能还想看看这个类似的问题:问题中的XML文档无效。XML文档需要有一个根元素。第一步是确保您的XML文档对生成类的XML模式有效。我尝试过使用这个模式,但给出了一个例外:@Kamal:请注意Blaise Doughan所说的。他是对的。您的xml文档中需要一个单独的根元素(在我的示例中,它被称为“People”)。@kamal-根据您在这里遇到的异常,您只需将
元素
变量更改为人
类型。已解决。。。非常感谢你们两个@用户278064@BlaiseDoughan@Blaise,@user278064:是的,我尝试在xml中添加根元素,给出了我在上一篇文章中提到的异常。这是我的xml文件:>>>>约翰>印度>>>史蒂夫>>解决了。。。非常感谢你们两个@用户278064@BlaiseDoughan
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<People>
<Employee>
<name>John</name>
<salary>5000</salary>
</Employee>
<Customer>
<name>Smith</name>
</Customer>
</People>
try {
File file = new File("D:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.generated");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement element = (JAXBElement) jaxbUnmarshaller.unmarshal(file);
People people = (People) element.getValue();
Employee employee = (Employee)people.getChildren().get(0); // the name of the getChildren() methodm may vary
Customer customer = (Customer)people.getChildren().get(1);
System.out.println(empObj.getName());
} catch (JAXBException e) {
e.printStackTrace();
}