Вы можете использовать Stax
-парсер.
Device
-класс (например):
public class Device {
private String name;
private String model;
public Device(String name, String model) {
this.name = name;
this.model = model;
}
//Getters & Setters
}
Parse Объект до xml использование XMLStreamWriter
:
List<Device> deviceList = ...
StringWriter stringWriter= new StringWriter();
XMLStreamWriter xmlWriter = XMLOutputFactory
.newFactory()
.createXMLStreamWriter(stringWriter);
xmlWriter.writeStartDocument();
xmlWriter.writeCharacters("\n");
xmlWriter.writeStartElement("devices"); // write <devices>
xmlWriter.writeCharacters("\n");
for(Device d : deviceList){
xmlWriter.writeCharacters("\t");
xmlWriter.writeStartElement("device"); // write <device>
xmlWriter.writeCharacters("\n\t\t");
xmlWriter.writeStartElement("name"); // write <name>
xmlWriter.writeCharacters(d.getName()); // write <name> value
xmlWriter.writeEndElement(); // write </name>
xmlWriter.writeCharacters("\n\t\t");
xmlWriter.writeStartElement("model"); // write <model>
xmlWriter.writeCharacters(d.getModel());// write <model> value
xmlWriter.writeEndElement(); // write </name>
xmlWriter.writeCharacters("\n\t");
xmlWriter.writeEndElement(); // write </device>
xmlWriter.writeCharacters("\n");
}
xmlWriter.writeEndElement(); // write </devices>
xmlWriter.writeEndDocument();
xmlWriter.close();
System.out.println(stringWriter.toString()); // print result
Результат:
<?xml version="1.0" ?>
<devices>
<device>
<name>iPhone</name>
<model>6s</model>
</device>
<device>
<name>iPhone</name>
<model>7</model>
</device>
<device>
<name>iPad</name>
<model>2</model>
</device>
</devices>