JAXB允许你deserialise XML转换成Java对象。如果创建Java POJO以匹配XML文档模型,则可以使用JAXB对POJO中的XML进行解组。
例如:
的POJO:
Report.java:
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Report {
private List<ReportRow> reportRows;
public List<ReportRow> getReportRows() {
return reportRows;
}
@XmlElement(name = "report_row")
public void setReportRows(List<ReportRow> reportRows) {
this.reportRows = reportRows;
}
}
ReportRow.java
import javax.xml.bind.annotation.XmlElement;
public class ReportRow {
private String c1;
private String c2;
private String c3;
private String c4;
public String getC1() {
return c1;
}
@XmlElement
public void setC1(String c1) {
this.c1 = c1;
}
public String getC2() {
return c2;
}
@XmlElement
public void setC2(String c2) {
this.c2 = c2;
}
public String getC3() {
return c3;
}
@XmlElement
public void setC3(String c3) {
this.c3 = c3;
}
public String getC4() {
return c4;
}
@XmlElement
public void setC4(String c4) {
this.c4 = c4;
}
}
代码来读取你的XML,并将其绑定到Java对象:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;
public class JaxbTest {
@Test
public void testFoo() throws JAXBException {
File xmlFile = new File("src/test/resources/reports.xml");
JAXBContext context = JAXBContext.newInstance(Report.class, ReportRow.class);
Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
Report report = (Report) jaxbUnmarshaller.unmarshal(xmlFile);
ReportRow reportYouWant = report.getReportRows().stream().filter(reportRow -> reportRow.getC1().equals("TDE-1"))
.findFirst().get();
}
}
您还需要以下依赖关系添加到您的构建脚本:
compile group: 'javax.xml', name: 'jaxb-impl', version: '2.1'
compile group: 'javax.xml', name: 'jaxb-api', version: '2.1'
究竟什么是“差异化”您在你的评论中谈到答案?这是直接的XML,只需要解析,不是吗?你能澄清确切的问题是什么吗? –
使用SAX或StaX来解析XML。读取标题时,您可以存储列描述。稍后在每一行中,您可以使用列描述来列关系来识别有趣的列。但不要指望我们为你编写整个代码。如果你被困住了,你应该自己开始并向我们展示你的代码。 – vanje
@vanje我按照你的建议编写了代码;但如果我的有趣数据位于最后一个元素,我将按顺序遍历xml文件的末尾。我正在寻找一条建议来优化我的代码,而不是原始代码。 –