ygyz03 2012-06-05 22:19 采纳率: 0%
浏览 325
已采纳

用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]
    希望大家能帮帮我,实在是解决不了了。

  • 写回答

3条回答 默认 最新

  • 晓星 2012-06-06 08:49
    关注

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

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

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

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘