我有以下需要解析的XML文件,我需要选择person_type值= 1的学生的名字。我在我的java项目中使用dom4j,我无法找到根据person_type的值提取firstname的解决方案。任何帮助将不胜感激。
<?xml version="1.0"?>
<class>
<student>
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
<person_types>
<person_type>1</person_type>
<person_description>POC</person_description>
</person_types>
</student>
<student>
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
<person_types>
<person_type>1</person_type>
<person_description>Assistant</person_description>
</person_types>
</student>
<student>
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
<person_types>
<person_type>1</person_type>`
<person_description>Leader</person_description>
</person_types>
</student>
</class>
答案 0 :(得分:0)
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<Node> nodes = document.selectNodes("/class/student" );
System.out.println("----------------------------");
for (Node node : nodes) {
if("1".equals(node.selectSingleNode("person_types").selectSingleNode("person_type").getText())){
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();
}
}