java Dom4j xml 写

手动拼接xml 并返回

依赖包

1          <dependency>
2             <groupId>dom4j</groupId>
3             <artifactId>dom4j</artifactId>
4             <version>1.6.1</version>
5         </dependency>

代码实现

 1 import org.dom4j.Document;
 2 import org.dom4j.DocumentHelper;
 3 import org.dom4j.Element;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RestController;
 6 
 7 @RestController
 8 @RequestMapping("/")
 9 public class XmlController {
10 
11     @RequestMapping(value = "/xmltest", produces = {"application/xml;charset=UTF-8"})
12     public String xml(String input) {
13 
14         try {
15             Document doucment = DocumentHelper.createDocument();
16             Element root = doucment.addElement("root");
17             Element author1 = root
18                     .addElement("author")
19                     .addAttribute("name", "tonyauto")
20                     .addAttribute("location", "UK")
21                     .addText("hello");
22 
23             Element author2 = root
24                     .addElement("author")
25                     .addAttribute("name", "toby")
26                     .addAttribute("location", "china")
27                     .addText("hello toby");
28             return doucment.asXML();
29         } catch (Exception ex) {
30             return "";
31         }
32     }
33 }

结果

1 <?xml version="1.0" encoding="UTF-8"?>
2 <root>
3     <author name="tonyauto" location="UK">hello</author>
4     <author name="toby" location="china">hello toby</author>
5 </root>
原文地址:https://www.cnblogs.com/tonyauto/p/8561628.html