你可以参考一下jdom提供的sample啊
这个结构很普遍的
很好读

解决方案 »

  1.   

    package jdom;import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.output.*;
    import java.io.*;
    import java.util.*;public Class Cute {public static void mAIn(String args[]) {
    try {
    /*
    * 用无变元构造函数构造一个SAXBuilder对象, 用sax解析器从文件中构造文档,
    * SAXBuilder侦听sax事件并从内存中建立一个相应的文档
    */
    SAXBuilder sb = new SAXBuilder();
    // 创建文档
    Document doc = sb.build(new FileInputStream("example.xml"));
    // 加入一条处理指令
    ProcessingInstruction pi = new ProcessingInstruction(
    "xml-stylesheet",
    "href=\"BOokList.html.xsl\" type=\"text/xsl\"");
    // 把这条处理指令,加入文档中
    doc.addContent(pi);
    // 获得这个文档的根元素
    Element root = doc.getRootElement();
    java.util.List ls = root.getChildren();
    // 获得这个根元素的所有子元素(不包含子元素的子元素),却完全忽略其内容 Iterator i = ls.iterator();while (i.hasNext()) {
    object o = i.next();
    if (o instanceof Text)/*使用instanceof 来获得所需要的内容*/
    {Text t=(Text)o;
    System.out.println("Text: " + t.getText());}
    else if(o instanceof Attribute)
    System.out.println("Attribute: " + o);
    else if (o instanceof Element)
    System.out.println("Element: " + ((Element) o).getName());
    }// 得到第一个子元素的子元素,却完全忽略其内容
    Element book = (Element) ls.get(0);
    // 给这个子元素添加一条属性,
    Attribute attr = new Attribute("hot", "true");
    book.setAttribute(attr);
    // 获得这个元素的子元素(指定)以及其值
    Element el2 = book.getChild("author");
    // 输出这个元素的值
    System.out.println(el2.getName());
    // 给这个元素的值改个名字
    el2.setText("cute");
    // 再获得这个元素的子元素(指定)
    Element el3 = book.getChild("price");
    // 给这个值换个值
    el3.setText(Float.tOString(50.0f));
    String indent = " ";
    boolean newLines = true;
    XMLOutputter xml = new XMLOutputter(indent, newLines, "gb2312");
    xml.output(doc, new FileOutputStream("e:\\cute.xml"));
    } catch (Exception e) {
    System.out.println(e.getMessage());}}
    }