org.w3c.dom.Document(标准java类库)

org.jdom.Document(JDOM9)都可以创建xml
并能输出。

解决方案 »

  1.   

    import org.apache.xerces.dom.DOMImplementation;
    import org.w3c.dom.DOMImplementation;
    import org.w3c.dom.Element;
    import org.apache.xml.serialize.XMLSerializer;
    import java.io.IOException;
    public class DomCreateExample{
    public static void main(String args[])throws IOException{
    Document dom=DOMImplementation.createDocument(null,null,null);
    Element root=dom.createElement("games");
    Element child1=dom.createElement("game");
    root.appendChild(child1);
    dom.appendChild(root);
    child1.setAttribute("genre","rpg");
    child1.appendChild(dom.createTextNode("Final Fantasy VII"));
    XMLSerializer serial=new XMLSerializer(System.out,null);
    serial.serialize(dom.getDocumentElement());

    }

    }
      

  2.   

    使用JDOM
    import org.jdom.*;
    import org.jdom.output.XMLOutputter;public class HelloJDOM {  public static void main(String[] args) {    Element root = new Element("GREETING");    root.addChild("Hello JDOM!");    Document doc = new Document(root);    // At this point the document only exists in memory.
        // We still need to serialize it
        XMLOutputter output = new XMLOutputter();
        try {
          output.output(doc, System.out);
        }
        catch (Exception e) {
          System.err.println(e);
        }  }}