XmlToTSV
XML から TSV に変換
■コード
package hello.org.xml.sax;
import java.io.File;
import java.io.FileInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XmlToTsv extends DefaultHandler {
int intend = 0;
String buff = null;
private void printIntend() {
for (int i = 0; i < intend; i++) {
System.out.print("\t");
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
printIntend();
System.out.print(qName);
int len = attributes.getLength();
for (int i = 0; i < len; i++) {
System.out.print("\t");
String name = attributes.getQName(i);
System.out.print("@" + name);
System.out.print("=");
String value = attributes.getValue(i);
System.out.print(value);
}
System.out.println();
intend++;
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (buff != null) {
printIntend();
System.out.println(buff);
buff = null;
}
intend--;
}
public void characters(char ch[], int start, int length)
throws SAXException {
String value = new String(ch, start, length);
// printIntend();
// System.out.println("(c)"+value);
buff = value;
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("arg[0] : xml file name");
System.exit(1);
return;
}
String filename = args[0];
File file = new File(filename);
if (file.exists() == false) {
System.err
.println("xml file not found : " + file.getAbsolutePath());
System.exit(1);
return;
}
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
XmlToTsv handler = new XmlToTsv();
saxParser.parse(new FileInputStream(file), handler);
}
}
■サンプルXML
<inventory>
<book year="2000">
<title>Snow Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553380958</isbn>
<price>14.95</price>
</book>
<book year="2005">
<title>Burning Tower</title>
<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>
<book year="1995">
<title>Zodiac</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553573862</isbn>
<price>7.50</price>
</book>
<!-- more books... -->
</inventory>
■実行結果例
inventory
book @year=2000
title
Snow Crash
author
Neal Stephenson
publisher
Spectra
isbn
0553380958
price
14.95
book @year=2005
title
Burning Tower
author
Larry Niven
author
Jerry Pournelle
publisher
isbn
0743416910
price
5.99
book @year=1995
title
Zodiac
author
Neal Stephenson
publisher
Spectra
isbn
0553573862
price
7.50
tags
---
XML TSV 変換