java - 如何使用 Jackson 将两个 XML 标记之间的内容提取为文本?
问题描述
我有一个带有以下模板的 XML:
<tag1 attr1="value1" attr2="value2">
<tag2> text </tag2>
<tag3> another text </tag3>
</tag1>
我想将此 xml 提取到具有 2 个文本字段String
和 2 个属性字段的 POJO 中,但我不太明白如何使用JacksonXmlText
.
解决方案
首先,从一些教程开始。例如,请查看此页面:使用 Jackson 将 XML 转换为 JSON。
一些关键点:
- 用于
com.fasterxml.jackson.dataformat.xml.XmlMapper
序列化/反序列化XML
- 使用此包中的注释
com.fasterxml.jackson.dataformat.xml.annotation
您的代码可能如下所示:
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
public class Main {
public static void main(String[] args) throws Exception {
XmlMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Tag1 tag1 = new Tag1();
tag1.setTag2("text");
tag1.setTag3("another text");
tag1.setAttribute1("value1");
tag1.setAttribute2("value2");
String xml = mapper.writeValueAsString(tag1);
System.out.println(xml);
System.out.println(mapper.readValue(xml, Tag1.class));
}
}
@JacksonXmlRootElement(localName = "tag1")
class Tag1 {
private String attribute1;
private String attribute2;
private String tag2;
private String tag3;
@JacksonXmlProperty(isAttribute = true)
public String getAttribute1() {
return attribute1;
}
public void setAttribute1(String attribute1) {
this.attribute1 = attribute1;
}
@JacksonXmlProperty(isAttribute = true)
public String getAttribute2() {
return attribute2;
}
public void setAttribute2(String attribute2) {
this.attribute2 = attribute2;
}
public String getTag2() {
return tag2;
}
public void setTag2(String tag2) {
this.tag2 = tag2;
}
public String getTag3() {
return tag3;
}
public void setTag3(String tag3) {
this.tag3 = tag3;
}
@Override
public String toString() {
return "Tag1{" +
"attribute1='" + attribute1 + '\'' +
", attribute2='" + attribute2 + '\'' +
", tag2='" + tag2 + '\'' +
", tag3='" + tag3 + '\'' +
'}';
}
}
上面的代码打印:
<tag1 attribute1="value1" attribute2="value2">
<tag2>text</tag2>
<tag3>another text</tag3>
</tag1>
Tag1{attribute1='value1', attribute2='value2', tag2='text', tag3='another text'}
推荐阅读
- devops - grafana GUI 出现“超出上下文截止日期”错误
- c++ - 解析文件时可以将 std::string_view 与 getline 一起使用吗?
- python - 遇到错误或程序结束后如何保持由selenium启动的chrome实例打开
- reactjs - 排序后状态没有在 React 中更新?
- android - 正确释放用于 Camera2 重复请求的目标 Surface
- excel - 隐藏文件夹中的〜$文件
- jquery - 等效于 jQuery 中的 document.createElement('option')
- java - 当Java中East = 0°时,根据角度计算新坐标
- c# - 如何在 C# 中测试 gRPC 拦截器?
- angular - 如何在 HttpErrorResponse 中获取正文消息?