您可以使用Jackson XML librairy 完成此操作。 Jackson 可能以JSON 序列化/反序列化而闻名,但它有一个 XML 扩展。
如果您的 XML 文件很大,请查看上面的链接,了解如何部分/增量读取它以获得最佳性能。
下面是一个示例,说明如何在您不想反序列化的字段上使用@JsonIgnore 注释仅读取属性的子集:
@JacksonXmlRootElement(localName = "jokes")
class Jokes {
@JacksonXmlProperty(localName = "joke")
@JacksonXmlElementWrapper(useWrapping = false)
private Joke[] jokes;
// getter, setter omitted
}
class Joke {
@JacksonXmlProperty(isAttribute = true)
long id;
@JacksonXmlProperty(localName = "title")
String title;
@JsonIgnore
String author;
@JacksonXmlProperty(localName = "like")
long like;
@JsonIgnore
String content;
public String toString() {
return Arrays.stream(new Object[] {id, title, author, like, content})
.map(o -> o!=null ? o.toString() : "EMPTY")
.collect(Collectors.joining(", ", "[", "]"));
}
// getters, setters omitted
}
带有示例文件:
<jokes>
<joke id="123">
<title>C'est l'histoire d'un mec</title>
<author>Coluche</author>
<content>Blah blah blah</content>
<like>4509</like>
</joke>
<joke id="777">
<title>Si j'ai bien tout lu freud</title>
<author>Coluche</author>
<content>Blah blah blah</content>
<like>345</like>
</joke>
</jokes>
还有main()
public class XmlJokeReader {
public static void main(String[] args) throws JsonProcessingException, IOException {
XmlMapper mapper = new XmlMapper();
Jokes jokesDoc = mapper.readValue(new File("./data/jokes.xml"), Jokes.class);
Arrays.stream(jokesDoc.getJokes()).forEach(j -> System.out.println(j.toString()));
}
}
输出是(注意 EMPTY 字段):
[123, C'est l'histoire d'un mec, EMPTY, 4509, EMPTY]
[777, Si j'ai bien tout lu freud, EMPTY, 345, EMPTY]
您还可以创建一个仅包含您需要的字段的 pojo - 然后不使用 @JsonIgnore。为此,XmlMapper 必须被告知忽略未知的 XML 属性。
XmlMapper mapper = new XmlMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
编辑
您想要一个只有几个字段的 pojo 的完整示例:
假设我们有一个只有id 和title 的pojo:
class Joke {
@JacksonXmlProperty(isAttribute = true)
long id;
@JacksonXmlProperty(localName = "title")
String title;
public String toString() {
return new StringBuffer().append('[')
.append(id).append(',')
.append(title).append(']').toString();
}
// getters setters
}
使用上述xml文件执行以下main():
公共类 XmlJokeReader {
public static void main(String[] args) throws JsonProcessingException, IOException {
XmlMapper mapper = new XmlMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Jokes jokesDoc = mapper.readValue(new File("./data/jokes.xml"), Jokes.class);
for (Joke joke : jokesDoc.getJokes()) {
System.out.println(joke.toString());
}
}
}
将给予:
[123,C'est l'histoire d'un mec]
[777,Si j'ai bien tout lu freud]