您可以在startElement
和endElement
中获取元素的名称。您还可以在startElement
中获取属性。应该在characters
中获取值。
以下是使用ContentHandler
获取元素值的非常基本的示例:
public class YourHandler extends DefaultHandler {
boolean inFirstNameElement = false;
public class startElement(....) {
if(qName.equals("firstName") {
inFirstNameElement = true;
}
}
public class endElement(....) {
if(qName.equals("firstName") {
inFirstNameElement = false;
}
}
public class characters(....) {
if(inFirstNameElement) {
}
}
}
如果您有一个简单的例子,为每个标签设置布尔标志是可以的。如果您有一个更复杂的场景,您可能更喜欢将标志存储在一个映射中,使用元素名称作为键,甚至创建一个或多个Employee
类映射到您的XML,在每次在startElement
中找到<employee>
时实例化它们,填充其属性,并在endElement
中添加到集合中。
这是一个完整的ContentHandler
示例,可与您的示例文件一起使用。希望能帮助您入门:
public class SimpleHandler extends DefaultHandler {
class Employee {
public String firstName;
public String lastName;
public String location;
public Map<String, String> attributes = new HashMap<>();
}
boolean isFirstName, isLastName, isLocation;
Employee currentEmployee;
List<Employee> employees = new ArrayList<>();
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if(qName.equals("employee")) {
currentEmployee = new Employee();
for(int i = 0; i < atts.getLength(); i++) {
currentEmployee.attributes.put(atts.getQName(i),atts.getValue(i));
}
}
if(qName.equals("firstName")) { isFirstName = true; }
if(qName.equals("lastName")) { isLastName = true; }
if(qName.equals("location")) { isLocation = true; }
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals("employee")) {
employees.add(currentEmployee);
currentEmployee = null;
}
if(qName.equals("firstName")) { isFirstName = false; }
if(qName.equals("lastName")) { isLastName = false; }
if(qName.equals("location")) { isLocation = false; }
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (isFirstName) {
currentEmployee.firstName = new String(ch, start, length);
}
if (isLastName) {
currentEmployee.lastName = new String(ch, start, length);
}
if (isLocation) {
currentEmployee.location = new String(ch, start, length);
}
}
@Override
public void endDocument() throws SAXException {
for(Employee e: employees) {
System.out.println("Employee ID: " + e.attributes.get("id"));
System.out.println(" First Name: " + e.firstName);
System.out.println(" Last Name: " + e.lastName);
System.out.println(" Location: " + e.location);
}
}
}