Java解析XML文件和JSON转换的方法(DOM4j解析)
在Java编程中,经常需要解析XML文件或者将JSON字符串转换成Java对象。针对这个问题,我们可以使用DOM4j解析库来处理。下面是详细的使用方法:
解析XML文件
引入依赖库
首先,需要在项目中引入dom4j和jaxen这两个依赖库。在Maven项目中,可以在项目的pom.xml文件中添加以下依赖:
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1-beta-6</version>
</dependency>
读取XML文件
下面是一个简单的示例代码,用于读取XML文件并解析其中的内容。
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
public class ReadXMLFile {
public static void main(String[] args) {
File inputFile = new File("input.xml");
SAXReader reader = new SAXReader();
try {
Document document = reader.read(inputFile);
Element root = document.getRootElement();
// 遍历根节点下的所有子节点
for (Iterator<Element> it = root.elementIterator(); it.hasNext(); ) {
Element element = it.next();
// 输出节点的名称和文本内容
System.out.println(element.getName() + ":" + element.getText());
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
在本示例中,我们首先创建了一个File对象表示输入的XML文件。然后创建一个SAXReader对象,并使用read()方法读取XML文件并转换成一个Document对象。接着,我们获取根节点Element对象,通过遍历根节点的所有子节点,输出节点的名称和文本内容。
创建XML文件
下面是一个示例代码,用于创建XML文件并添加节点。
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CreateXMLFile {
public static void main(String[] args) {
Document document = DocumentHelper.createDocument();
Element company = document.addElement("company");
company.addAttribute("name", "ABC Company");
Element department = company.addElement("department");
department.addAttribute("name", "IT Department");
Element employee1 = department.addElement("employee");
employee1.addAttribute("id", "1001");
employee1.addElement("name").setText("Tom");
employee1.addElement("age").setText("25");
Element employee2 = department.addElement("employee");
employee2.addAttribute("id", "1002");
employee2.addElement("name").setText("Jerry");
employee2.addElement("age").setText("28");
try {
XMLWriter writer = new XMLWriter(new FileWriter(new File("output.xml")), OutputFormat.createPrettyPrint());
writer.write(document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在本示例中,我们首先创建一个Document对象,然后向其添加根节点和子节点及其属性。最后,我们创建一个XMLWriter对象,将Document对象写入到一个文件中。
JSON转换
以下是一个JSON字符串:
{
"name": "Jack",
"age": 24,
"sex": "male",
"hobbies": ["reading", "swimming", "traveling"],
"address": {
"city": "Shanghai",
"street": "Xujiahui Road"
}
}
我们可以将其转换成一个Java对象,代码如下:
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class ConvertJSONToJava {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Jack\",\"age\":24,\"sex\":\"male\",\"hobbies\":[\"reading\",\"swimming\",\"traveling\"],\"address\":{\"city\":\"Shanghai\",\"street\":\"Xujiahui Road\"}}";
User user = JSON.parseObject(jsonStr, User.class);
System.out.println(user.getName() + "," + user.getAge() + "," + user.getSex());
System.out.println("Hobbies:");
List<String> hobbies = user.getHobbies();
for (String hobby : hobbies) {
System.out.println(hobby);
}
Address address = user.getAddress();
System.out.println("Address:");
System.out.println(address.getCity() + "," + address.getStreet());
}
}
class User {
private String name;
private int age;
private String sex;
private List<String> hobbies = new ArrayList<>();
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
class Address {
private String city;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
在本示例中,我们首先定义了一个Java类User和一个内部类Address,用于描述JSON字符串中的数据结构。然后,我们使用FastJson库的JSON.parseObject()方法将JSON字符串转换成User对象。最后,我们输出User对象的属性值。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java解析xml文件和json转换的方法(DOM4j解析) - Python技术站