-1
我在一個文件夾中有幾個XML文件。我想將XML數據文件寫入文本文件。但我不明白該怎麼做。 :(將XML數據文件寫入文本文件
示例XML文件:
<?xml version = "1.0"?>
<note>
<to> Mat </to>
<from> Tim </from>
<head> Black </head>
<body> Yellow </body>
</note>
這裏是我的代碼:
public class ReadXML extends DefaultHandler {
Boolean noteTag = false;
Boolean toTag = false;
Boolean fromTag = false;
Boolean headTag = false;
Boolean bodyTag = false;
static final String NOTE = "note";
static final String TO = "to";
static final String FROM = "from";
static final String HEAD = "head";
static final String BODY = "body";
public void read() throws Exception {
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
File folder = new File("D:\\Source Code\\NetBeans\\Java\\BGPU\\ParseXMLFile");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile() && file.getName().endsWith(".xml")) {
saxParser.parse(file, this);
System.out.println();
}
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase(NOTE)) {
noteTag = true;
}
if (qName.equalsIgnoreCase(TO)) {
toTag = true;
}
if (qName.equalsIgnoreCase(FROM)) {
fromTag = true;
}
if (qName.equalsIgnoreCase(HEAD)) {
headTag = true;
}
if (qName.equalsIgnoreCase(BODY)) {
bodyTag = true;
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (fromTag.equals(true)) {
System.out.println("FROM: " + new String(ch, start, length));
}
if (toTag.equals(true)) {
System.out.println("TO: " + new String(ch, start, length));
toTag = false;
}
if (headTag.equals(true)) {
System.out.println("HEAD: " + new String(ch, start, length));
headTag = false;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase(NOTE)) {
noteTag = false;
}
if (qName.equalsIgnoreCase(TO)) {
toTag = false;
}
if (qName.equalsIgnoreCase(FROM)) {
fromTag = false;
}
if (qName.equalsIgnoreCase(HEAD)) {
headTag = false;
}
if (qName.equalsIgnoreCase(BODY)) {
bodyTag = false;
}
}
public void save(String filename) throws Exception {
}
請幫我完成save()方法
特別任何理由使用SAX解析器的更清潔的方式?您可以將文件複製到任何文件而無需解析內容:http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java – 2014-09-27 05:45:52
我只使用SAX,如果文件太大而不適合內存。 – Adam 2014-09-27 06:01:29