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
应该给我一个没有命名空间的名字。我做错了吗?
答案 0 :(得分:6)
尝试识别SAXParserFactory命名空间:
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
SAXParser saxParser = saxParserFactory.newSAXParser();
阅读startElement()here的详细信息。您会看到localName
不是&#39;除非解析器知道名称空间,否则定义。