springboot 解析复杂xml
时间: 2023-07-08 15:41:42 浏览: 60
当XML文件比较复杂时,使用JAXB可能会变得不太方便,这时你可以使用DOM或SAX等更高级的XML解析库。下面是一个使用DOM解析复杂XML文件的示例:
1. 在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
```
2. 创建一个控制器类,使用DOM解析XML数据:
```
@RestController
@RequestMapping("/api")
public class XmlController {
@PostMapping("/xml")
public String parseXml(@RequestBody String xmlString) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlString));
Document document = db.parse(is);
NodeList nodeList = document.getElementsByTagName("person");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String name = element.getElementsByTagName("name").item(0).getTextContent();
int age = Integer.parseInt(element.getElementsByTagName("age").item(0).getTextContent());
sb.append("Name: ").append(name).append(", Age: ").append(age).append("\n");
}
}
return sb.toString();
}
}
```
在上面的示例中,我们使用了DocumentBuilderFactory和DocumentBuilder来创建一个XML文档的DOM表示。然后,我们使用getNodeList方法获取所有的person元素,并逐个解析它们的子元素。
3. 使用Postman或其他HTTP客户端进行测试:
发送POST请求到http://localhost:8080/api/xml,将以下XML数据作为请求体:
```
<?xml version="1.0" encoding="UTF-8"?>
<people>
<person>
<name>John Doe</name>
<age>30</age>
</person>
<person>
<name>Jane Smith</name>
<age>25</age>
</person>
</people>
```
如果一切正常,你应该会得到以下响应:
```
Name: John Doe, Age: 30
Name: Jane Smith, Age: 25
```
这就是使用Spring Boot解析复杂XML文件的一个示例。注意,你可以使用其他XML解析库,例如SAX,来处理更大的XML文件。