如何在Java中读取具有给定值的特定XML节点

时间:2018-02-20 22:03:04

标签: java xml dom xml-parsing

给出如下的XML内容。

当我只传递rollno的值时,是否有可以返回整个学生节点的API。例如,如果我通过 493 ,那么我应该获得493的学生信息以及所有子元素,如名字,姓氏,...标记等



<?xml version = "1.0"?>
<class>
<old>
   <student rollno = "393">
      <firstname>dinkar</firstname>
      <lastname>kad</lastname>
      <nickname>dinkar</nickname>
      <marks>85</marks>
   </student>   
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>vinni</nickname>
      <marks>95</marks>
   </student>
</old>
<current>
   <student rollno = "593">
      <firstname>jasvir</firstname>
      <lastname>singn</lastname>
      <nickname>jazz</nickname>
      <marks>90</marks>
   </student>
    <student rollno = "125">
      <firstname>abcd</firstname>
      <lastname>defc</lastname>
      <nickname>dumy</nickname>
      <marks>90</marks>
   </student>
    <student rollno = "965">
      <firstname>xyz</firstname>
      <lastname>defc</lastname>
      <nickname>sample</nickname>
      <marks>90</marks>
   </student>
</current>
</class>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

不确定是否通过一次调用获取整个集合,但您可以获取每个标记的值...类似于:

File fXmlFile = new File("student.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();


NodeList nList = doc.getElementsByTagName("student");


for (int temp = 0; temp < nList.getLength(); temp++) {
    Node nNode = nList.item(temp);

 if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        System.out.println("Student rollno : "
                           + eElement.getAttribute("rollno"));
        System.out.println("Firstname : "
                           + eElement.getElementsByTagName("firstname")
                             .item(0).getTextContent());
        System.out.println("Last Name : "
                           + eElement.getElementsByTagName("lastname")
                             .item(0).getTextContent());
        System.out.println("Nickname : "
                           + eElement.getElementsByTagName("nickname")
                             .item(0).getTextContent());
        System.out.println("Marks : "
                           + eElement.getElementsByTagName("marks")
                             .item(0).getTextContent());
    }
}