Java JDOM解析器 - 查詢XML文檔

演示示例

這是需要我們查詢的輸入XML文件:

Ferarri 101 Ferarri 201 Ferarri 301 Lamborgini 001 Lamborgini 002 Lamborgini 003 Benteley 1 Benteley 2 Benteley 3

演示示例:

QueryXmlFileDemo.java

import java.io.File; import java.io.IOException; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class QueryXmlFileDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); System.out.println("Root element :" + document.getRootElement().getName()); Element classElement = document.getRootElement(); List<Element> supercarList = classElement.getChildren("supercars"); System.out.println("----------------------------"); for (int temp = 0; temp < supercarList.size(); temp++) { Element supercarElement = supercarList.get(temp); System.out.println("\nCurrent Element :" + supercarElement.getName()); Attribute attribute = supercarElement.getAttribute("company"); System.out.println("company : " + attribute.getValue() ); List<Element> carNameList = supercarElement.getChildren("carname"); for (int count = 0; count < carNameList.size(); count++) { Element carElement = carNameList.get(count); System.out.print("car name : "); System.out.println(carElement.getText()); System.out.print("car type : "); Attribute typeAttribute = carElement.getAttribute("type"); if(typeAttribute !=null) System.out.println(typeAttribute.getValue()); else{ System.out.println(""); } } } }catch(JDOMException e){ e.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } } }

這將產生以下結果:

Root element :cars

Current Element :supercars
company : Ferrari
car name : Ferarri 101
car type : formula one
car name : Ferarri 201
car type : sports car
car name : Ferarri 301
car type : sports car

Current Element :supercars
company : Lamborgini
car name : Lamborgini 001
car type :
car name : Lamborgini 002
car type :
car name : Lamborgini 003
car type :