Reputation: 111
I want to get a tag from another tag specified with an attribute I have chosen. In this XML file for example, how do I proceed to print the mark 85 of the student 393?
<?xml version="1.0"?>
<class>
<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>
<class>
I am writing in Java and using JDom as follows
NodeList nList = doc.getElementsByTagName("student");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
Element eElement = (Element) nNode;
System.out.println("Student roll no : " + eElement.getAttribute("rollno"));
System.out.println("First Name : "+ eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : "+ eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Marks : " + eElement.getElementsByTagName("marks").item(0).getTextContent());
}
Thank you!
Upvotes: 2
Views: 181
Reputation: 89325
You can use the following XPath expression to find student
element having rollno
attribute equals 393
and then return the corresponding marks
child element :
//student[@rollno='393']/marks
I'm not familiar with JDom or Java in general, but JDom seems to support XPath :
Upvotes: 1