import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class Main {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input.xml");
Root root = (Root) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
@XmlRootElement
public static class Root {
private int[][] matrix;
@XmlJavaTypeAdapter(MatrixAdapter.class)
public int[][] getMatrix() {
return matrix;
}
public void setMatrix(int[][] matrix) {
this.matrix = matrix;
}
}
public static class MatrixAdapter extends
XmlAdapter<MatrixAdapter.AdaptedMatrix, int[][]> {
public static class AdaptedMatrix {
@XmlElement(name = "row")
public List<AdaptedRow> rows;
}
public static class AdaptedRow {
@XmlValue
public int[] row;
}
@Override
public AdaptedMatrix marshal(int[][] matrix) throws Exception {
AdaptedMatrix adaptedMatrix = new AdaptedMatrix();
adaptedMatrix.rows = new ArrayList<AdaptedRow>(matrix.length);
for (int[] row : matrix) {
AdaptedRow adaptedRow = new AdaptedRow();
adaptedRow.row = row;
adaptedMatrix.rows.add(adaptedRow);
}
return adaptedMatrix;
}
@Override
public int[][] unmarshal(AdaptedMatrix adaptedMatrix) throws Exception {
List<AdaptedRow> adaptedRows = adaptedMatrix.rows;
int[][] matrix = new int[adaptedRows.size()][];
for (int x = 0; x < adaptedRows.size(); x++) {
matrix[x] = adaptedRows.get(x).row;
}
return matrix;
}
}
}
input.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<matrix>
<row>1 2 3 4</row>
<row>5 6 7 8</row>
</matrix>
</root>