Java xml转对象
时间: 2023-09-20 14:06:12 浏览: 67
在Java中,可以使用JAXB(Java Architecture for XML Binding)库将XML文档转换为Java对象。以下是一个基本的示例:
假设我们有一个XML文档如下:
```xml
<person>
<name>John Doe</name>
<age>30</age>
<address>
<street>123 Main St</street>
<city>Anytown</city>
<state>CA</state>
<zip>12345</zip>
</address>
</person>
```
我们可以使用JAXB将其转换为以下Java对象:
```java
public class Person {
private String name;
private int age;
private Address address;
// getters and setters
}
public class Address {
private String street;
private String city;
private String state;
private String zip;
// getters and setters
}
```
我们需要创建一个JAXBContext对象,然后使用它创建一个Unmarshaller对象,然后使用Unmarshaller对象将XML文档转换为Java对象。以下是完整的示例代码:
```java
import javax.xml.bind.*;
import java.io.File;
public class XmlToObject {
public static void main(String[] args) throws JAXBException {
File file = new File("person.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Person person = (Person) jaxbUnmarshaller.unmarshal(file);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.getAddress().getStreet());
System.out.println(person.getAddress().getCity());
System.out.println(person.getAddress().getState());
System.out.println(person.getAddress().getZip());
}
}
```
运行该程序将输出以下内容:
```
John Doe
30
123 Main St
Anytown
CA
12345
```
阅读全文