ノードとサブノードを含む 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
どんな助けでも感謝されます。