`
orange5458
  • 浏览: 348294 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

XML JAVA解析 -- DOM4J

    博客分类:
  • XML
阅读更多

1. 实例

 

package com.siyuan.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DOM4JTest {
 
 public static void printElement(Element e) {
  System.out.println("Element : " + e.getName() + "---------------");
  
  List attributes = e.attributes();
  Iterator iterAttrs = attributes.iterator();
  while (iterAttrs.hasNext()) {
   Attribute attri = (Attribute) iterAttrs.next();
   System.out.println("Attribute " + attri.getName() + "=" + attri.getValue());
  }
  
  System.out.println(e.getText());
  
  List children = e.elements();
  Iterator iter = children.iterator();
  while (iter.hasNext()) {
   printElement((Element) iter.next());
  }
 }
 
 /**
  * @param args
  * @throws DocumentException
  * @throws IOException
  */
 public static void main(String[] args) throws DocumentException, IOException {
  // TODO Auto-generated method stub
  SAXReader reader = new SAXReader();
  reader.setValidation(true);
  Document doc = reader.read("src/com/siyuan/xml/workers.xml");
  printElement(doc.getRootElement());
  
  XMLWriter writer = new XMLWriter(new FileOutputStream(new File("src/com/siyuan/xml/workers3.xml")));
  writer.write(doc);
  writer.close();
 }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics