我如何读取具有节点然后再具有子节点的xml文件,并且该子节点可以进一步具有子节点
像 XML 文件
<?xml version="1.0" encoding="UTF-8"?>
<school>
<student id="1">
<firstname name="ankush">
<test>sample </test> //......here can be more sub nodes
</firstname>
<lastname>thakur</lastname>
<email>beingjavaguy.gmail.com</email>
<phone>7678767656</phone>
</student>
</school>
我曾经阅读过的代码:
public class ReadXml extends DefaultHandler{
public void getXml(){
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
DefaultHandler defaultHandler = new DefaultHandler(){
String firstNameTag="close";
String lastNameTag="close";
String emailTag="close";
String phoneTag="close";
String testTag="close";
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("FIRSTNAME")) {
firstNameTag = "open";
}
if (qName.equalsIgnoreCase("TEST")) {
testTag = "open";
}
if (qName.equalsIgnoreCase("LASTNAME")) {
lastNameTag = "open";
}
if (qName.equalsIgnoreCase("EMAIL")) {
emailTag = "open";
}
if (qName.equalsIgnoreCase("PHONE")) {
phoneTag = "open";
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (firstNameTag.equals("open")) {
System.out.println("First Name : " + new String(ch, start, length));
}
if (testTag.equals("open")) {
System.out.println("Test Name : " + new String(ch, start, length));
}
if (lastNameTag.equals("open")) {
System.out.println("Last Name : " + new String(ch, start, length));
}
if (emailTag.equals("open")) {
System.out.println("Email : " + new String(ch, start, length));
}
if (phoneTag.equals("open")) {
System.out.println("Phone : " + new String(ch, start, length));
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("firstName")) {
firstNameTag = "close";
}
if (qName.equalsIgnoreCase("test")) {
testTag = "close";
}
if (qName.equalsIgnoreCase("lastName")) {
lastNameTag = "close";
}
if (qName.equalsIgnoreCase("email")) {
emailTag = "close";
}
if (qName.equalsIgnoreCase("phone")) {
phoneTag = "close";
}
}
};
saxParser.parse("xmlToRead/student.xml", defaultHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
但输出
First Name :
First Name : sample
Test Name : sample
First Name :
Last Name : thakur
Email : beingjavaguy.gmail.com
Phone : 7678767656
任何帮助将不胜感激。