OpenJDK 16.0.1
javac WriteXML.java
java WriteXML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<people>
<person age="20" name="taro"/>
<person age="23" name="hanako"/>
<person age="16" name="foobar"/>
</people>
import java.io.StringWriter; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.Writer; | |
import java.util.ArrayList; | |
import java.util.List; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import javax.xml.parsers.ParserConfigurationException; | |
import javax.xml.transform.OutputKeys; | |
import javax.xml.transform.TransformerConfigurationException; | |
import javax.xml.transform.TransformerException; | |
import javax.xml.transform.TransformerFactory; | |
import javax.xml.transform.dom.DOMSource; | |
import javax.xml.transform.stream.StreamResult; | |
import org.w3c.dom.Element; | |
import org.xml.sax.SAXException; | |
public class WriteXML { | |
public static void main(String... args) { | |
List<Person> people = new ArrayList<>(); | |
people.add(new Person("taro", 20)); | |
people.add(new Person("hanako", 23)); | |
people.add(new Person("foobar", 16)); | |
try (Writer w = new StringWriter()) { | |
writeXML(w, people); | |
var s = w.toString(); | |
System.out.println(s); | |
} catch (Exception e) {} | |
} | |
private static void writeXML(Writer writer, List<Person> people) | |
throws ParserConfigurationException, TransformerConfigurationException, TransformerException { | |
var factory = DocumentBuilderFactory.newInstance(); | |
var builder = factory.newDocumentBuilder(); | |
var document = builder.newDocument(); | |
var root = document.createElement("people"); | |
document.appendChild(root); | |
people.stream() | |
.forEach( | |
item -> { | |
var elem = document.createElement("person"); | |
elem.setAttribute("name", item.name); | |
elem.setAttribute("age", "" + item.age); | |
root.appendChild(elem); | |
}); | |
var transformerFactory = TransformerFactory.newInstance(); | |
var transformer = transformerFactory.newTransformer(); | |
var domSource = new DOMSource(document); | |
var streamResult = new StreamResult(writer); | |
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); | |
transformer.transform(domSource, streamResult); | |
} | |
} | |
class Person { | |
final String name; | |
final int age; | |
Person(String name, int age) { | |
this.name = name; | |
this.age = age; | |
} | |
} |