用sax解析xml文件把读取的内容写入txt

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.util.HashSet;

import java.util.Set;


import javax.xml.parsers.ParserConfigurationException;

import javax.xml.parsers.SAXParser;

扫描二维码关注公众号,回复: 830715 查看本文章

import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.Attributes;

import org.xml.sax.InputSource;

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;


import com.incesoft.xmas.commons.StringUtils;


public class MyXml extends DefaultHandler {

java.util.Stack tags = new java.util.Stack();

static Set<String> set = new HashSet<String>();


StringBuffer str = new StringBuffer();


public MyXml() {

super();

}


@Override

public void characters(char[] ch, int start, int length) throws SAXException {

String tag = (String) tags.peek();

if (tag.equals("category")) {

str.append(new String(ch, start, length));

}

}


@Override

public void startElement(String uri, String localName, String name, Attributes attributes)

throws SAXException {

tags.push(name);

}


@Override

public void endElement(String uri, String localName, String name) throws SAXException {

if (name.equals("category")) {

String strs = str.toString().trim();

if (StringUtils.isNotBlank(strs)) {

if (set.add(str.toString().trim())) {

writeTxtFile("D:\\1.txt", str.toString().trim());

System.out.println("|" + str.toString().trim() + "|");

}

}

str.setLength(0);

}

}


public static void main(String[] args) {

File file = new File("D:\\1.txt");

if (!file.exists()) {

try {

file.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

}

try {

SAXParserFactory sf = SAXParserFactory.newInstance();

SAXParser sp = sf.newSAXParser();

MyXml reader = new MyXml();

sp.parse(new InputSource("D://00.xml"), reader);

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}


public static void writeTxtFile(String filename, String info) {

// 先读取原有文件内容,然后进行写入操作

String message = info + "\r\n";

BufferedWriter fw = null;

try {

// fw = new FileWriter(fileName);

OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filename, true), "GBK");

// out.append(message);

fw = new BufferedWriter(out);

fw.append(message);

fw.flush();

// fw.append(message);

// fw.flush();

} catch (IOException e1) {

e1.printStackTrace();

} finally {

if (fw != null) {

try {

fw.close();

} catch (IOException e2) {

e2.printStackTrace();

}

}

}

}

}

猜你喜欢

转载自yrandy.iteye.com/blog/1634779
今日推荐