DOM4J解析XML转写TXT

books.xml

<?xml version="1.0" encoding="UTF-8"?>
<books> 
  <book>
       <title>Dom4j Tutorials</title>
  </book>
  <book>
       <title>Lucene Studing</title>
  </book>
  <book>
       <title>Lucene in Action</title>
  </book>
  <owner>O'Reilly</owner>
</books> 

package com.hy.dao;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class dom4j {
 BufferedWriter bw = null;

 public void printXML(String filepath) throws IOException {
  bw = new BufferedWriter(new FileWriter(filepath)); // 写文件位置
  bw.write("<?xml version='1.0' encoding='GB2312'?>");
  try {
   SAXReader sreader = new SAXReader();//
   File file = new File("");//
   Document document = sreader.read(new File(file.getAbsolutePath()
     + "//webRoot//books.xml")); // 读取文件
   Element root = document.getRootElement(); // 获得文件的根节点元素
   printtree(root, 0);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void printtree(Element node, int i) throws IOException {

  bw.write("<"); // 打印一个节点开始"<"

  String name = node.getName(); // 得到根节点名
  bw.write(name); // 打印节点的名字
  bw.write(" >"); // 打印节点的结束">";
  if (!"".equals(node.getText())) { // 判断是不是有文本值
   bw.write(node.getText());
  }
  
  
  // 此处开始递归调用
  Iterator ite = node.elementIterator(); // 迭代根元素下面的所有子节点
  while (ite.hasNext()) { // 判断是否有下一个元素
   Element snode = (Element) ite.next();
   printtree(snode, i + 2);
  }
  bw.write("</" + name + ">");
  bw.flush();
 }
}

test.java

package com.hy.dao;

import java.io.IOException;

public class test {

 public static void main(String[] argv) throws IOException {
  String filepath = "E:/dom4j.txt";    //写入的文件路径
  dom4j ptree = new dom4j();
  ptree.printXML(filepath);
 }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值