如何使用 Java 和 SAX 解析我的简单 XML 文件?
我正在尝试解析下面的文件.我想打印每位乘客的身份证和姓名.能给我代码解析一下吗?
I am trying to parse the file below. I want to print the id and name of each passenger. Can you give me code to parse it ?
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:android="www.google.com">
<passenger id = "001">
<name>Tom Cruise</name>
</passenger>
<passenger id = "002">
<name>Tom Hanks</name>
</passenger>
</root>
更新这是我尝试过的.这里提到的代码、问题等 -简单 SAX 解析器输出错误
UPDATE This is what i had tried. Code, problems etc mentioned here - Error in output of a simple SAX parser
推荐答案
下面是一个工作示例,虽然我建议你改用 StAX,但你会发现 SAX 不是很方便
Here is a working example to start with, though I suggest you to use StAX instead, you will see that SAX is not very convenient
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAX2 {
public static void main(String[] args) throws Exception {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new File("test.xml"), new DefaultHandler() {
@Override
public void startElement(String uri, String localName,
String qName, Attributes atts) throws SAXException {
if (qName.equals("passenger")) {
System.out.println("id = " + atts.getValue(0));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String text = new String(ch, start, length);
if (!text.trim().isEmpty()) {
System.out.println("name " + text);
}
}
});
}
}
输出
id = 001
name Tom Cruise
id = 002
name Tom Hanks
相关文章