DOM解析器を使ってXMLを作成します.
1.以下はDOMを使ってXMLドキュメントを作成するコードです.
import java.io.StringWriter;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class DOMCreate
{
public static void main( String[] args )
{
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element root = doc.createElement("Student");
Element item = doc.createElement(" ");
item.appendChild( doc.createTextNode(" ") );
root.appendChild( item );
item = doc.createElement("age");
item.appendChild( doc.createTextNode("28" ) );
root.appendChild( item );
item = doc.createElement("high");
item.appendChild( doc.createTextNode("1.72" ) );
root.appendChild( item );
item = doc.createElement("score");
Element lesson = doc.createElement("Java");
lesson.appendChild(doc.createTextNode("95"));
item.appendChild( lesson );
lesson = doc.createElement("Struts");
lesson.appendChild(doc.createTextNode("90"));
item.appendChild( lesson );
lesson = doc.createElement("Hibernate");
lesson.appendChild(doc.createTextNode("90"));
item.appendChild( lesson );
root.appendChild( item );
doc.appendChild( root );
OutputFormat format = new OutputFormat( doc , "GBK" , true );
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer( stringOut, format );
serial.asDOMSerializer();
serial.serialize( doc.getDocumentElement() );
PrintStream ps = new PrintStream(new FileOutputStream("d:/new.xml"));
ps.println(stringOut.toString());
System.out.println( "STRXML = " + stringOut.toString() ); //Spit out DOM as a String
}
catch ( Exception ex )
{
ex.printStackTrace();
}
}
}
2.プログラムを変更して作成したXML文書は以下の通りです.<?xml version="1.0" encoding="GBK"?>
<Student>
< > </ >
<age>28</age>
<high>1.72</high>
<score>
<Java>95</Java>
<Struts>90</Struts>
<Hibernate>90</Hibernate>
</score>
</Student>