我需要解析 XML 文件以获取 xml 文件中存在的标签的值。我已经完成了部分工作,并且卡在了中间。我的 xml 文件如下,(示例 xml 文件)
<?xml version="1.0" encoding="UTF-8"?>
<database>
<student name="abc">
<phone>6879987</phone>
<dept>eee</dept>
<college>act</college>
<semester>
<year>2</year>
<no.of.sub>7</no.of.sub>
</semester>
<hostel>
<year>3</year>
<block>d4</block>
</hostel>
</student>
<student name="ram">
<phone>65464</phone>
<dept>cse</dept>
<college>Mit</college>
<semester>
<year>4</year>
<no.of.sub>5</no.of.sub>
</semester>
<hostel>
<year>5</year
<block>y4</block>
</hostel>
</student>
</database>
我的实现如下,
public class MySaxParser extends DefaultHandler {
private String temp;
private ArrayList<Account> accList = new ArrayList<Account>();
private Account acct;
public static void main(String[] args) throws IOException, SAXException,
ParserConfigurationException {
SAXParserFactory spfac = SAXParserFactory.newInstance();
SAXParser sp = spfac.newSAXParser();
MySaxParser handler = new MySaxParser();
sp.parse("test.xml", handler);
handler.readList();
}
@Override
public void characters(char[] buffer, int start, int length) {
temp = new String(buffer, start, length);
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
temp = "";
if (qName.equalsIgnoreCase("Student")) {
acct = new Account();
//acct.setType(attributes.getValue("type"));
}
}
@override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("Student")) {
// add it to the list
accList.add(acct);
} else if (qName.equalsIgnoreCase("phone")) {
acct.setphone(temp);
} else if (qName.equalsIgnoreCase("dept")) {
acct.setdept((temp));
} else if (qName.equalsIgnoreCase("College")) {
acct.setcollege(temp);
}
}
private void readList() {
Iterator<Account> it = accList.iterator();
while (it.hasNext()) {
System.out.println(it.next().toString());
}
}
}
我可以解析 phone, dept college 的值。但是年标签是学期和宿舍的子标签。我需要同时获得年份值。当我简单地使用时,
else if (qName.equalsIgnoreCase("year")) {
acct.setyear(temp);
只有宿舍的年份值被打印跳过学期。1)我如何解析这些子标签。提前致谢