您的位置:首页 > 其它

使用sax读取xml文件生成txt文件。

2016-08-19 15:34 405 查看
package read;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Stack;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
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;

public class MyXMLReader2SAX extends DefaultHandler {
private boolean isStart;
Stack<String> tags = new Stack<String>();

public MyXMLReader2SAX() {
super();
isStart = false;
}

public static void main(String args[]) throws IOException, ParserConfigurationException, SAXException {

File f = new File("out.txt");
f.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(f);
PrintStream printStream = new PrintStream(fileOutputStream);
System.setOut(printStream);

SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
MyXMLReader2SAX reader = new MyXMLReader2SAX();
sp.parse(new InputSource("sourcedate.xml"), reader);
}

@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (isStart && !tags.isEmpty()) {

String tName = tags.pop();
if (tName.equals("Description")) {
System.out.print("~");
}
System.out.print(new String(ch, start, length).trim() + " ");
if (tName.equals("Description")) {
System.out.println();
}
}

}

public void startElement(String uri, String localName, String qName, Attributes attrs) {
switch (qName) {
case "Name":
case "Description":
isStart = true;
tags.push(qName);
}
}

public void endtElement(String uri, String localName, String qName, Attributes attrs) {
isStart = false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: