I have a few XML files in one folder. I want to write the XML data file into a text file. But I don't understand how to do it. :(
Sample XML file:
<?xml version = "1.0"?>
<note>
<to> Mat </to>
<from> Tim </from>
<head> Black </head>
<body> Yellow </body>
</note>
Here is my code:
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 {
}
Please help me to finish the save() method.