SimpleXmlWriter
これでも実用上は問題なし。
■コード
package hello.javax.xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class SimpleXmlWriter {
public void writeXml() throws Exception {
File tempFile = File
.createTempFile("test", ".xml", new File("c:/temp"));
System.out.println(tempFile.getAbsolutePath());
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(tempFile), "UTF-8");
PrintWriter out = new PrintWriter(writer);
out.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.printf("<cars>\n");
out.printf("<car vin=\"%s\">\n", "123fhg5869705iop90");
out.printf("<make>%s</make>\n",escape("Toyota"));
out.printf("<model>%s</model>\n",escape("Prius"));
out.printf("</car>\n");
out.printf("</cars>\n");
out.flush();
out.close();
}
static private String escape(String str) {
if (str == null) {
return null;
}
char c;
StringBuffer sb = new StringBuffer();
int length = str.length();
for (int idx = 0; idx < length; idx++) {
c = str.charAt(idx);
if (c == '<') {
sb = sb.append("<");
} else if (c == '>') {
sb = sb.append(">");
} else if (c == '&') {
sb = sb.append("&");
} else if (c == '"') {
sb = sb.append(""");
} else {
sb = sb.append(c);
}
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
SimpleXmlWriter obj = new SimpleXmlWriter();
obj.writeXml();
}
}
■出力されるファイル
<?xml version="1.0" encoding="UTF-8"?>
<cars>
<car vin="123fhg5869705iop90">
<make>Toyota</make>
<model>Prius</model>
</car>
</cars>