我有一个以下格式的xml文件,作为服务的响应。它不是传统的xml格式,其中值包含在相应的标记内。它只是一个示例,而实际文件将有数百个元素。如何以最有效的方式到达我需要的节点(让我们说“TDE-2'”)并将其值放在{map(TenderID, TDE-2), map(ContactID, null)}
<xml version="1.0" encoding="UTF-8"?>
<report>
<report_header>
<c1>TenderID</c1>
<c2>ContactID</c2>
<c3>Address</c3>
<c4>Description</c4>
<c5>Date</c5>
</report_header>
<report_row>
<c1>TDE-1</c1>
<c2></c2>
<c3></c3>
<c4>Tender 1</c4>
<c5>09/30/2016</c5>
</report_row>
<report_row>
<c1>TDE-2</c1>
<c2></c2>
<c3></c3>
<c4>Tender 2</c4>
<c5>10/02/2016</c5>
</report_row>
</report>
答案 0 :(得分:1)
JAXB允许您将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'