要使用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文件。