我正在通过SAX XML解析器解析一个简单的XML文件,并在列表视图中显示结果。这是成功完成的。现在我想在abc标签关闭时像下面的XML文件那样做。然后下面的标签项不解析(苹果不添加列表视图)。谁能帮我。 Thanx提前
<abc>
<employee>
<name>Android</name>
</employee>
<employee>
<name>Nokia</name>
</employee>
</abc>
<employee>
<name>Apple</name>
</employee>
这是我正在使用的SAXXMLHandler
public class SAXXMLHandler extends DefaultHandler {
private List<Employee> employees;
private String tempVal;
private Employee tempEmp;
public SAXXMLHandler() {
employees = new ArrayList<Employee>();
}
public List<Employee> getEmployees() {
return employees;
}
// Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("employee")) {
// create a new instance of employee
tempEmp = new Employee();
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("employee")) {
// add it to the list
employees.add(tempEmp);
} else if (qName.equalsIgnoreCase("name")) {
tempEmp.setName(tempVal);
}
}
}
答案 0 :(得分:1)
维护一个boolean
来控制哪个员工姓名应该添加到列表中,哪个不应该......如下所示......
public class SAXXMLHandler extends DefaultHandler {
private List<Employee> employees;
private String tempVal;
private Employee tempEmp;
private boolean shouldAdd = false;
public SAXXMLHandler() {
employees = new ArrayList<Employee>();
}
public List<Employee> getEmployees() {
return employees;
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
tempVal = "";
if (qName.equalsIgnoreCase("abc")) {
shouldAdd = true;
} else if (qName.equalsIgnoreCase("employee")) {
// create a new instance of employee
tempEmp = new Employee();
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("abc") && shouldAdd == true) {
shouldAdd = false;
} else if (qName.equalsIgnoreCase("employee") && shouldAdd == true) {
// add it to the list
employees.add(tempEmp);
} else if (qName.equalsIgnoreCase("name")) {
tempEmp.setName(tempVal);
}
}
}