📅  最后修改于: 2020-11-14 10:32:34             🧑  作者: Mango
这是我们需要解析的输入xml文件-
dinkar
kad
dinkar
85
Vaneet
Gupta
vinni
95
jasvir
singn
jazz
90
package com.tutorialspoint.xml;
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class DOM4JQueryDemo {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
SAXReader reader = new SAXReader();
Document document = reader.read( inputFile );
System.out.println("Root element :" + document.getRootElement().getName());
Element classElement = document.getRootElement();
List nodes = document.selectNodes("/class/student[@rollno = '493']" );
System.out.println("----------------------------");
for (Node node : nodes) {
System.out.println("\nCurrent Element :"
+ node.getName());
System.out.println("Student roll no : "
+ node.valueOf("@rollno") );
System.out.println("First Name : "
+ node.selectSingleNode("firstname").getText());
System.out.println("Last Name : "
+ node.selectSingleNode("lastname").getText());
System.out.println("First Name : "
+ node.selectSingleNode("nickname").getText());
System.out.println("Marks : "
+ node.selectSingleNode("marks").getText());
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
这将产生以下结果-
Root element :class
----------------------------
Current Element :student
Student roll no : 493
First Name : Vaneet
Last Name : Gupta
First Name : vinni
Marks : 95