Java Reference
In-Depth Information
to an .xml file. This sample code comes from the
org.java8recipes.chapter20.recipe20_1.DocWriter example:
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
...
public void run(String outputFile) throws
FileNotFoundException, XMLStreamException,
IOException {
List<Patient> patients = new ArrayList<>();
Patient p1 = new Patient();
Patient p2 = new Patient();
Patient p3 = new Patient();
p1.setId(BigInteger.valueOf(1));
p1.setName("John Smith");
p1.setDiagnosis("Common Cold");
p2.setId(BigInteger.valueOf(2));
p2.setName("Jane Doe");
p2.setDiagnosis("Broken Ankle");
p3.setId(BigInteger.valueOf(3));
p3.setName("Jack Brown");
p3.setDiagnosis("Food Allergy");
patients.add(p1);
patients.add(p2);
patients.add(p3);
XMLOutputFactory factory
= XMLOutputFactory.newFactory();
try (FileOutputStream fos = new
FileOutputStream(outputFile)) {
XMLStreamWriter writer
= factory.createXMLStreamWriter(fos, "UTF-8");
writer.writeStartDocument();
writer.writeCharacters("\n");
writer.writeStartElement("patients");
writer.writeCharacters("\n");
for (Patient p : patients) {
writer.writeCharacters("\t");
Search WWH ::




Custom Search