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;
}
}
使用sax读取xml文件生成txt文件。
最新推荐文章于 2023-11-18 15:37:31 发布