我正在尝试解析下面的文件。我想打印每位乘客的身份和姓名。你能给我解析它的代码吗?
<?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>
更新 这就是我尝试过的。这里提到的代码,问题等 - Error in output of a simple SAX parser
答案 0 :(得分:2)
这是一个开始的工作示例,虽然我建议您使用StAX,但您会看到SAX不是很方便
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
答案 1 :(得分:1)
DocumentBuilderFactory
。DocumentBuilder
。parse()
方法之一创建Document
。Document
后,您可以使用Document
的{{1}}方法获取乘客Element
。我相信你能够解决剩下的问题。
答案 2 :(得分:0)
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
InputStream xmlInput = new FileInputStream("theFile.xml");
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new SaxHandler();
saxParser.parse(xmlInput, handler);
} catch (Throwable err) {
err.printStackTrace ();
}
答案 3 :(得分:0)
String str = "<?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>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(str));
final Document document = db.parse(is);
System.out.println("node Name " + document.getChildNodes().item(0).getChildNodes().item(1).getNodeName());