我要300分。
解决样例如下:
public class TestReplace
{
    static String xmlContent;
    public static void init()
    {
        xmlContent = "<?xml version=\"1.0\" encoding=\"GB2312\"?>"
            + "<lib>"
            + "<book>"
            + "<name>Java</name>"
            + "<author>zhang</author>"
            + "<pub>qinghua</pub>"
            + "<price>35.0</price>"
            + "<pubdate>2002-10-07</pubdate>"
            + "</book>"
            + "<book>"
            + "<name>XML</name>"
            + "<author>li</author>"
            + "<pub>hope</pub>"
            + "<price>92.0</price>"
            + "<pubdate>2002-10-07</pubdate>"
            + "</book>"
            + "</lib>";
    }    public static void replaceXML()
    {
        try
        {
            org.jdom.input.SAXBuilder sb = new org.jdom.input.SAXBuilder();
            System.out.println(xmlContent);
            org.jdom.Document doc = sb.build(new java.io.
                                             StringBufferInputStream(xmlContent));
            org.jdom.Element root = doc.getRootElement(); //得到根元素
            java.util.List books = root.getChildren(); //得到根元素所有子元素的集合
            org.jdom.Element book = null;
            for (int i = 0; i < books.size(); i++)
            {
                book = (org.jdom.Element) books.get(i); //得到第一本书元素
                book.getChild("price").setText("100");
            }
            org.jdom.output.XMLOutputter outer = new org.jdom.output.
                XMLOutputter();
            java.io.StringWriter sw = new java.io.StringWriter();
            outer.output(doc, sw);
            System.out.println(sw.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }    public static void main(String[] args)
    {
        init();
        replaceXML();
    }
}

解决方案 »

  1.   

    上面的程序把xml内的所有price字段数值都改变为100了。
      

  2.   

    Thanks anyways.But your code isn't what I want.What I mean is <price> --> <other_element>.
      

  3.   

    楼主,我只是举个例子,你自己举一反三不就可以了?
    “<price> --> <other_element>”
    你需要替换什么元素自己换好了,难道代码写的还不明白吗?But your code isn't what I want.What I mean is .
      

  4.   

    book.getChild("price").setText("100");?
    当然,没问题。as for Element, 你能保证新element和旧element在JDom tree中的位置不变吗?think it over.
      

  5.   

    是不变的。“as for Element, 你能保证新element和旧element在JDom tree中的位置不变吗?”
      

  6.   

    对于element的替换,你只能remove the old element, than append a new one.
    这样,the new element 只能是其父节点的childen的最后一个。难道位置不是变了吗?我找到了一种解决办法,就是先把JDOM 转化成DOM,再replace,然后如果需要,
    再DOM-->JDOM.
    该方法我已实现。
    当然,效率不知会怎么样。