猿问

用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") ;
    }
    }

    • 希望大家能帮帮我,实在是解决不了了。



Smart猫小萌
浏览 637回答 2
2回答

守候你守候我

第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?我out了 还是楼主碉堡了 :oops:
随时随地看视频慕课网APP

相关分类

Java
我要回答