dom4j解析XML

来源:互联网 发布:剑灵花钱吗 知乎 编辑:程序博客网 时间:2024/05/02 03:31

package com.lxy.tool.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class MyXMLReader {
 public static void main(String arge[]) {
  SAXReader reader = new SAXReader();
  try {
   Document document = reader.read(new File("F://JMM//articles.xml"));
   System.out.println(document.getXMLEncoding());
   Element root = document.getRootElement();//根节点
   print(root);//遍厉整个文档
   writeToFile(document,"Jwk_Issue(UTF-8)-1154.xml","UTF-8");//写入xml文件

  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 public static void print(Element elm) {
  if (elm.isTextOnly())
   System.out.println(elm.getText());
  else {
   List nodes = elm.elements();
   for (Iterator it = nodes.iterator(); it.hasNext();) {
    Element e = (Element) it.next();
    // System.out.println(e.getName());
    print(e);
   }
  }
 }

 public static void writeToFile(Document doc, String filePath,
   String encoding) {
  try {
   OutputFormat fmt = OutputFormat.createPrettyPrint();
   fmt.setEncoding(encoding);

   XMLWriter xmlWriter = new XMLWriter(new OutputStreamWriter(
     new FileOutputStream(filePath), encoding), fmt);
   xmlWriter.write(doc);
   xmlWriter.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

原创粉丝点击