LocalName返回空字符串,但定义了名称空间

时间:2014-06-11 19:02:36

标签: java xml sax saxparser

XML

<em:Employees  xmlns:em="http://www.example.com">
    <em:Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
        <childrens>
            <child>
                <age>2</age>
                <name>Guptha</name>
                <gender>Male</gender>
            </child>
        </childrens>
    </em:Employee>
</em:Employees>

爪哇

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class XMLParserSAX {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxParserFactory.newSAXParser();
        MyHandler handler = new MyHandler();
        saxParser.parse(new File("src/Resources/employees.xml"), handler);
        //Get Employees list
        List<Employee> empList = handler.getEmpList();
        //print employee information
        for (Employee emp : empList)
            System.out.println(emp);
    }
}

在我的DefaultHandler中,当我实现startElement()时,localName为空,qName包含名称空间,包括名称,ex。 em:Employees

如果我没弄错的话,localName应该给我一个没有命名空间的名字。我做错了吗?

1 个答案:

答案 0 :(得分:6)

尝试识别SAXParserFactory命名空间:

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    SAXParser saxParser = saxParserFactory.newSAXParser();

阅读startElement()here的详细信息。您会看到localName不是&#39;除非解析器知道名称空间,否则定义。