读取条件年龄> 30的XML文件并在Java控制台中输出

时间:2015-01-21 10:55:44

标签: java xml sax

我正在Eclipse中读取XML文件,而我的输出在我的控制台中。 到目前为止,我设法输出我的条目。 但是我需要打印我的员工超过30岁的条目。

这是我的XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<company>
    <name>CompanyName</name>
    <employees id="0">
        <name>employee name0</name>
        <age>33</age>
        <role>tester</role>
        <gen>male</gen>
    </employees>
    <employees id="1">
        <name>employee name1</name>
        <age>18</age>
        <role>tester</role>
        <gen>female</gen>
    </employees>
    <employees id="2">
        <name>employee name2</name>
        <age>38</age>
        <role>developer</role>
        <gen>male</gen>
    </employees>
    </company>

这就是我一直在尝试的:

if (qName.equals("age"))
{
  int age2;
  String age=attributes.getValue("age");
   age2=Integer.ParseInt(age)
if (age2>30){
System.out.println("\tAge="+age2);
}

所以我要打印

id = 0的员工和id = 2的员工,因为他们的年龄> 30

1 个答案:

答案 0 :(得分:0)

考虑到您正在使用SAXParser并且此代码段位于重写方法startElement内,您还需要覆盖charactersendElement。像这样:

class Handler extends DefaultHandler {

String currentElement;
String currentAgeValue;
String currentNameValue;

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    super.startElement(uri, localName, qName, attributes);
    currentElement = qName;
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException {
    super.characters(ch, start, length);
    switch(currentElement) {
        case "age":
        currentAgeValue = new String(ch, start, length);
        break;
        case "name":
        currentNameValue = new String(ch, start, length);
        break;
    }
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    super.endElement(uri, localName, qName);
    if(qName.equals("employees")) {
        int age = Integer.parseInt(currentAgeValue);
        if(age > 30) { 
            System.out.println("Name:" + currentNameValue+", Age:" + age);
        }
    }
}

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
    String xml = "<company><name>CompanyName</name><employees id=\"0\"><name>employee name0</name><age>33</age><role>tester</role><gen>male</gen></employees><employees id=\"1\"><name>employee name1</name><age>18</age><role>tester</role><gen>female</gen></employees><employees id=\"2\"><name>employee name2</name><age>38</age><role>developer</role><gen>male</gen></employees></company>";
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(new InputSource(new StringReader(xml)), new Handler());
}

输出将是:

Name:employee name0, Age:33
Name:employee name2, Age:38

在读取给定元素的值时调用characters方法,startElement的Attribute参数保留<employees id="2"> id 等XML属性的值