📅  最后修改于: 2020-11-14 10:27:43             🧑  作者: Mango
这是我们需要查询的输入xml文件-
Ferarri 101
Ferarri 201
Ferarri 301
Lamborgini 001
Lamborgini 002
Lamborgini 003
Benteley 1
Benteley 2
Benteley 3
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 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 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 :