JDOM--处理XML节点

public class MendXML {

 /\*\*
  \* @param args
  \*/
 private Document doc=null;
 
 public void setRootNode(String fileName){
  SAXBuilder sax=new SAXBuilder(false);
  try {
   doc=sax.build(fileName);
  } catch (JDOMException e) {
   e.printStackTrace();
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 public void mendXML(){
  if(doc!=null){
   Element rootElement=doc.getRootElement();
   rootElement.removeContent(0);
   rootElement.removeChild("book");
   //删除根元素下第一个<book>元素的id属性
   rootElement.getChild("book").setAttribute("id","0");
   //获得第8个内容节点,并修改其内容
   Element element=(Element)rootElement.getContent(7);
   element.removeContent();
   element.addContent("1111");
   
  }else{
   return ;
  }
 }
 
 public void outputXML(String fileName){
  XMLOutputter outer=new XMLOutputter();
  Format format=Format.getPrettyFormat();
  format.setIndent("  ");
  try {
   format.setEncoding("GB2312");
   outer.setFormat(format);
   FileWriter writer = new FileWriter(fileName);
   outer.output(doc, writer);
   writer.close();
  } catch (Exception e) {
   // TODO: handle exception
  }
 }
 
 public static void main(String[] args) {
   MendXML mender=new MendXML();
   mender.setRootNode("e:/project/JDOM/1.xml");
   mender.mendXML();
   mender.outputXML("e:/project/JDOM/1modified.xml");
 }

}
在上一日志的1.xml文件的基础上修改如下:

<?xml version="1.0" encoding="GB2312"?>
<books>
  <!--The sample class for Handling XML-->
  <book id="0">2</book>
  <book id="2">3</book>
  <book id="3">1111</book>
</books>

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Wei Guan

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today