【问题标题】:LocalName is returning empty string, though namespace is definedLocalName 返回空字符串,尽管命名空间已定义
【发布时间】:2014-06-11 19:02:35
【问题描述】:

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>

Java

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 包含名称空间,例如名称。 em:Employees.

如果我没记错的话,localName 应该给我没有命名空间的名称。我是不是做错了什么?

【问题讨论】:

  • 它对我有用,你能分享代码的相关部分吗?特别是您创建 XMLReader 的部分
  • @morgano 我没有使用 XMLReader,我使用的是 SAXParser。我已经在上面发布了我的代码。

标签: java xml sax saxparser


【解决方案1】:

尝试让 SAXParserFactory 命名空间感知:

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

阅读 startElement() here 的详细信息。你会看到 localNameisn' 被定义,除非解析器知道命名空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多