springboot使用jackson解析XML
maven依赖
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
一个xml例子
<?xml version="1.0" encoding="UTF-8"?>
<book>
<remote name="java" url="http://bookstack.cn/" />
<remote name="c" url="http://jianshu.cn/" />
<remote name="javascript" url="http://www.w3school.com.cn/" />
<default name="java" />
<project name="Java核心技术" author="Cay S. Horstmann" />
<project name="Learning Spring Boot 2.0" author="Greg L. Turnquist" />
</book>
定义好java bean
@Data
@JacksonXmlRootElement(localName = "book") //root根是book
@JsonIgnoreProperties(ignoreUnknown = true)
public class Book {
@JacksonXmlElementWrapper(useWrapping = false) //remote是一个没有list包围的list
private List<Remote> remote;
@JacksonXmlElementWrapper(useWrapping = false)
private List<Project> project;
@JacksonXmlProperty(localName = "default") //default是保留字,不能作为bean名称,因此用localname指定
private DefaultEle defaultvalue;
}
定义下层的bean
@Data
@JsonIgnoreProperties(ignoreUnknown = true) //忽略掉xml里不关注的element
public class Project {
@JacksonXmlProperty(isAttribute = true) //name是project的attribute属性,不是value
private String name;
}
java代码
InputStream input = Main.class.getResourceAsStream("/book.xml");
JacksonXmlModule module = new JacksonXmlModule();
XmlMapper mapper = new XmlMapper(module);
try {
Book book = mapper.readValue(input, Book.class);
System.out.println(book.getProject().get(0).getName());
} catch (IOException e) {
e.printStackTrace();
}
网友评论