wjjbfq 发表于 2013-1-15 02:56:01

java利用dom4j来操作xml文件

使用dom4j操作xml文件可以参考dom4j的api文档。
 
1、parsing XML 解析xml文件
SAXReader reader = new SAXReader();File file =new File("xx.xml");Document document = reader.read(file);2、获取根元素
Element root = document.getRootElement();3、获取所有的元素、获取某个特定的元素、获取根元素的属性
// iterate through child elements of root      for ( Iterator i = root.elementIterator(); i.hasNext(); ) {            Element element = (Element) i.next();            // do something      }      // iterate through child elements of root with element name "foo"      for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {            Element foo = (Element) i.next();            // do something      }      // iterate through attributes of root         for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {            Attribute attribute = (Attribute) i.next();            // do something      } 4、将document写入文件
//prepare an output format,which has new line .打印(显示)出来有格式OutputFormat format = OutputFormat.createPrettyPrint();format.setIndentSize(4);//OutputStream os = new FileOutputStream(fileName);//output stream ( where to output )and format (how to output)XMLWriter writer = new XMLWriter(os,format);//output content( what to be output)---documentwriter.write(document);writer.close(); 
 使用例子
1、在xml文件中增加element
      步骤:1、open the document and get the rootDocument;
               2、construct an element ;
               3、append the newly element to the root element;
               4、update the count of the root element;此处是更新根元素的count属性,如果没有这个属性则不需要更新,count属性存储element 的个数。
               5、save the document into the file.
 
页: [1]
查看完整版本: java利用dom4j来操作xml文件