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
包含 namespace ,前任。 em:员工
。
如果我没记错的话,localName
应该会返回不带 namespace 的名称。我做错了什么吗?
最佳答案
尝试让 SAXParserFactory 命名空间感知:
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
SAXParser saxParser = saxParserFactory.newSAXParser();
阅读 startElement() 的详细信息 here .您会看到 localName
未定义,除非解析器知道 namespace 。
关于java - LocalName 返回空字符串,尽管命名空间已定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24170630/