xml在指定节点下新增节点

        String savePath = Config . getResultTemplatePath () ;//xml文本路径
         SAXReader saxReader = new SAXReader () ;
         Document document = saxReader . read ( savePath ) ;
         Element root = document . getRootElement () ;
        Element acknowledgementNode = root . element ( "acknowledgement" ) ;
         String Str = acknowledgementNode . asXML () ;
         System . out . println ( "student1 字符串:" + Str ) ;
         List < Element > listElement = root . elements () ;
         Iterator iterator = listElement . iterator () ;
         while ( iterator . hasNext ()) {
             Element e = ( Element ) iterator . next () ;
             String eleName = e . getName () ;
             // 如果id==1 则添加新的节点
             if ( "sender" . equals ( eleName )) {
                 // 新添加的节点
                 e . add (( Element ) acknowledgementNode . clone ()) ;
             }
         }
注意点:element对象的add(Element)方法,如果只是e.add(Element)是会报错的,只有通过复制后指定添加element节点e.add((Element) acknowledgementNode.clone());

你可能感兴趣的:(xml,dom4j)