使用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>

 

你可能感兴趣的:(java,apache,Hibernate,xml,struts)