用Jdom向web.xml添加节点出错

想通过Jdom向web.xml文件添加servlet的配置信息。如:

xxx
com.sdt.action.xxx


xxx
/xxx

但是总是报这样的错误:Exception in thread "main" org.jdom.IllegalAddException: The Content already has an existing parent "servlet"
我的代码如下:
[code="java"]import java.io.File;
import java.io.FileOutputStream;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Parent;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**向web.xml中增加Servlet配置
*

  • @author liujia
    */
    public class DomUtil {

    public static void add(String tableName) throws Exception {
    String className = "PersonServlet" ;
    String servletPackage = "com.sdt.servlet" ;

    String fileName = "d:/netbeans/workday01/src/test/javaeye/web.xml" ;
    File f = new File(fileName) ;
    SAXBuilder builder = new SAXBuilder() ;
    Document doc = builder.build(f) ;
    Element root = doc.getRootElement() ;
    System.out.println("root: " + root.getName());
    Element servlet = new Element("servlet") ;
    Element servletMapping = new Element("servlet-mapping") ;
    Element servletName = new Element("servletName") ;
    Element servletClass = new Element("servletClass") ;
    Element urlPattern = new Element("urlPattern") ;
    
    servletClass.setText(servletPackage + "." + className) ;
    servletName.setText("className") ;
    urlPattern.setText("/" + className) ;
    
    servlet.addContent(servletName) ;
    servlet.addContent(servletClass) ;
    servletMapping.addContent(servletName) ;
    servletMapping.addContent(urlPattern) ;
    
    Parent p = root.getParent();
    p.removeContent(root);
    root.addContent(servlet) ;
    root.addContent(servletMapping) ;
    
    XMLOutputter out = new XMLOutputter() ;
    out.setFormat(out.getFormat().setEncoding("GBK")) ;
    out.output(doc, new FileOutputStream(new File(fileName),true)) ;
    

    }

    public static void main(String[] args) throws Exception {
    add("t_person") ;
    }
    }[/code]
    希望大家能帮帮我,实在是解决不了了。

第26行代码 Element servlet = new Element("servlet") ;

servlet节点不能共享,只能是一个节点的子节点,不能即是a节点的子节点又是b节点的子节点
也就是说解决你的问题在于
第38行代码
servletMapping.addContent(servletName) ;

处修改为
servletMapping.addContent( new Element("servletName")) ;

另外42行处
p.removeContent(root);

干什么吧根节点给删除了?
如果跟节点删除了,没有根节点
那么document就不完整了,你后面也没有显示的增加,所以,是你的思路的问题;再好好的整理一下!

这个功能有用吗?web.xml不是在服务器启动的时候加载的吗?

楼主竟然运行时改web.xml?
我out了 还是楼主碉堡了 :oops: