import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.sql.*;
import org.apache.crimson.tree.*;public class WriterXml {  public static void ha() {
    System.out.println("ahahahhaha");
  }
  public static void main(String[] args) {
    Document doc = null;
    Element students;
    Element stud;
    Element fName;
    Element sName;
    try {
      DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
      doc = dBuilder.newDocument();      stud = doc.createElement("Student");
      fName = doc.createElement("FirstName");
      fName.appendChild(doc.createTextNode("Chen"));
      stud.appendChild(fName);
      sName = doc.createElement("Surname");
      sName.appendChild(doc.createTextNode("Liancong"));
      stud.appendChild(sName);
      students = doc.createElement("Students");
      students.setAttribute("Department","Mathematics");      students.appendChild(stud);
      doc.appendChild(students);
      //((XmlDocument)doc).write(System.out);
      ((XmlDocument)doc).write(new FileOutputStream("d:\\a.txt"));
    }catch(Exception e) {
      e.printStackTrace();
    }
  }
}

解决方案 »

  1.   

    用dom4j,很简单的
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;public class Foo {    public Document createDocument() {
            Document document = DocumentHelper.createDocument();
            Element root = document.addElement( "root" );        Element author1 = root.addElement( "author" )
                .addAttribute( "name", "James" )
                .addAttribute( "location", "UK" )
                .addText( "James Strachan" );
            
            Element author2 = root.addElement( "author" )
                .addAttribute( "name", "Bob" )
                .addAttribute( "location", "US" )
                .addText( "Bob McWhirter" );        return document;
        }
    }