Skip to content

Instantly share code, notes, and snippets.

@jiro4989
Last active December 23, 2021 14:47
Show Gist options
  • Save jiro4989/3bb6c64d511d19de74bfe7079fd732b0 to your computer and use it in GitHub Desktop.
Save jiro4989/3bb6c64d511d19de74bfe7079fd732b0 to your computer and use it in GitHub Desktop.
JavaでObjectからXMLを生成して標準出力に書き出す
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;
}
}

前提条件

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment