634 - JAXP - SAX - プログラム - タグの取得Advertisement処理手順
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
public class SAXTest extends DefaultHandler {
private static int tab;
public static void main(String[] args) {
tab = 0;
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
BufferedInputStream input =
new BufferedInputStream(new FileInputStream(new File("c:\\sample.xml")));
// SAXパーサ取得
SAXParser saxParser = saxParserFactory.newSAXParser();
InputSource inputSource = new InputSource(input);
// パース
saxParser.parse(inputSource, new SAXTest());
}catch (Exception e){
System.err.println(e);
}
}
// 要素の開始通知
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts){
for(int i = 0; i < tab; i++){
System.out.print("\t");
}
System.out.println("<" + qName + ">");
tab = tab + 1;
}
// 要素の終了通知
public void endElement(String namespaceURI,
String localName,
String qName){
tab = tab - 1;
for(int i = 0; i < tab; i++){
System.out.print("\t");
}
System.out.println("</" + qName + ">");
}
}
読み込みファイル(sample.xml)
<document>
<book>
<title>Java</title>
<price>1000</price>
</book>
<book>
<title>XML</title>
<price>1500</price>
</book>
</document>
処理結果
<document>
<book>
<title>
</title>
<price>
</price>
</book>
<book>
<title>
</title>
<price>
</price>
</book>
</document>
|