gpt4 book ai didi

java - 简单 SAX 解析器的输出错误

转载 作者:行者123 更新时间:2023-12-01 15:00:00 25 4
gpt4 key购买 nike

我在mykong看到了一个例子 - http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/我尝试通过对上面页面中的代码进行以下修改来使其适用于 xml 文件(如下) -

1 - Have only two if blocks in startElement() and characters() methods.
2 - Change the print statements in above methods, ie
FIRSTNAME and First Name = passenger id
LASTNAME and Last Name = name

问题是 - 在输出中,我看到了“passenger”一词,而不是“passenger id”的值。我该如何解决这个问题?

<?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>

Java 代码

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 ReadXMLFileSAX{

public static void main(String argv[]) {

try {

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {

boolean bfname = false;
boolean blname = false;

public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {

System.out.println("Start Element :" + qName);

if (qName.equalsIgnoreCase("passenger id")) {
bfname = true;
}

if (qName.equalsIgnoreCase("name")) {
blname = true;
}

}

public void endElement(String uri, String localName,
String qName) throws SAXException {

System.out.println("End Element :" + qName);

}

public void characters(char ch[], int start, int length) throws SAXException {

if (bfname) {
System.out.println("passenger id : " + new String(ch, start, length));
bfname = false;
}

if (blname) {
System.out.println("name : " + new String(ch, start, length));
blname = false;
}

}

};

saxParser.parse("c:\\flight.xml", handler);

} catch (Exception e) {
e.printStackTrace();
}

}

}

最佳答案

在 startElement 中,当它是“passenger”时,您获得的 Attributes 参数将具有该值。

public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("passenger") && attributes != null){
System.out.println(attributes.getValue("id"));
}
}

关于java - 简单 SAX 解析器的输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13798038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com