JAXB allows you to deserialise XML into Java Objects. If you create Java POJOs to match the XML document model, you can then use JAXB to unmarshal the XML in the POJO.
for example:
POJOs:
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;
}
}
Code to read your XML and bind it into java objects:
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();
}
}
You also need to add the following dependencies to your build script:
compile group: 'javax.xml', name: 'jaxb-impl', version: '2.1'
compile group: 'javax.xml', name: 'jaxb-api', version: '2.1'