复制番号代番号次のように:
パッケージ com.test;
java.io.ファイルをインポートします。
java.io.FileInputStreamをインポートします。
java.util.ArrayListをインポートします。
java.util.Listをインポートします。
インポート javax.xml.parsers.SAXParser;
インポート javax.xml.parsers.SAXParserFactory;
org.xml.sax.Attributes をインポートします。
org.xml.sax.SAXException をインポートします。
org.xml.sax.helpers.DefaultHandler をインポートします。
パブリック クラス SaxXML {
public static void main(String[] args) {
ファイル file = new File("e:/People.xml");
試す {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser パーサー = spf.newSAXParser();
SaxHandler ハンドラー = new SaxHandler("People");
parser.parse(新しい FileInputStream(ファイル), ハンドラー);
List<People> peopleList = handler.getPeoples();
for(人 人 : peopleList){
System.out.println(people.getId()+"/t"+people.getName()+"/t"+people.getEnglishName()+"/t"+people.getAge());
}
} catch (例外 e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}
クラス SaxHandler extends DefaultHandler {
private List<People> people = null;
プライベート 人々;
プライベート文字列 currentTag = null;
プライベート文字列 currentValue = null;
プライベート文字列ノード名 = null;
public List<People> getPeoples() {
人々を帰還させます。
}
public SaxHandler(String ノード名) {
this.nodeName = ノード名;
}
@オーバーライド
public void startDocument() は SAXException をスローします {
// TODO が開始のタイミングに達したら、このメソッドに問い合わせます
super.startDocument();
peoples = new ArrayList<People>();
}
@オーバーライド
public void endDocument() は SAXException をスローします {
// TODO自動生成の方法が存在する
super.endDocument();
}
@オーバーライド
public void startElement(String uri, String localName, String name,
属性attributes) throws SAXException {
// TODO当たって文档の开头的候、调用この方法
super.startElement(uri, localName, name, 属性);
if (name.equals(nodeName)) {
人 = 新しい People();
}
if (属性 != null && 人 != null) {
for (int i = 0; i <attributs.getLength(); i++) {
if(attributes.getQName(i).equals("id")){
people.setId(attributes.getValue(i));
}
else if(attributes.getQName(i).equals("en")){
people.setEnglishName(attributes.getValue(i));
}
}
}
現在のタグ = 名前;
}
@オーバーライド
public void 文字(char[] ch, int start, int length)
SAXException をスローします {
// TODO このメソッドは、XML ファイル内の読み込まれたコンテンツを処理するために使用されます
super.characters(ch, 開始, 長さ);
if (currentTag != null && people != null) {
currentValue = 新しい文字列(ch, 開始, 長さ);
if (currentValue != null && !currentValue.trim().equals("") && !currentValue.trim().equals("/n")) {
if(currentTag.equals("名前")){
people.setName(currentValue);
}
else if(currentTag.equals("年齢")){
people.setAge(currentValue);
}
}
}
現在のタグ = null;
現在の値 = null;
}
@オーバーライド
public void endElement(String uri, String localName, String name)
SAXException をスローします {
// TODO 在遇到结束标签的候,调用这个方法
super.endElement(uri, localName, name);
if (name.equals(nodeName)) {
peoples.add(人);
}
}
}