要使用Java对XML文件进行转换,你可以使用一些流行的库,如JAXB(Java Architecture for XML Binding)和DOM(Document Object Model)。这里我将向你展示如何使用JAXB库将XML文件转换为Java对象,以及如何将Java对象转换回XML文件。
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
person.xml
的XML文件,其结构如下:<person>
<name>John Doe</name>
<age>30</age>
</person>
为了将这个XML文件转换为Java对象,你需要创建一个名为Person.java
的Java类:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "person")
public class Person {
private String name;
private int age;
@XmlElement
public void setName(String name) {
this.name = name;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class XmlToJava {
public static void main(String[] args) {
try {
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() + ", " + person.getAge());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
public class JavaToXml {
public static void main(String[] args) {
try {
File file = new File("person.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Person person = new Person();
person.setName("Jane Doe");
person.setAge(28);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
jaxbMarshaller.marshal(person, file);
System.out.println("XML file has been created successfully.");
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
现在你可以运行XmlToJava
类将person.xml
文件转换为Java对象,然后运行JavaToXml
类将Java对象转换回XML文件。