我正在使用SAXParser解析XML并尝试获取特定节点的值,但我的代码正在返回null
。我不知道自己做错了什么。这是我的代码。任何帮助将不胜感激。
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserUsage extends DefaultHandler {
SAXParserFactory factory;
SAXParser parser;
DefaultHandler handler;
private String elementName;
private String authorizationCode;
public String getAuthCodeResponse(String message) throws SAXException, IOException, ParserConfigurationException {
factory = SAXParserFactory.newInstance();
handler = new SAXParserUsage();
parser = factory.newSAXParser();
parser.parse(new InputSource(new StringReader(message)), handler);
return authorizationCode;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
elementName = qName;
}
public void characters(char[] text, int start, int length) throws SAXException {
if (elementName.equals("code")) {
String code = new String(text, start, length);
System.out.println("setting code: " + code);
authorizationCode = code;
}
}
public void endElement(String arg0, String arg1, String arg2) throws SAXException {
}
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
SAXParserUsage usage = new SAXParserUsage();
String code = usage.getAuthCodeResponse(getSampleString());
System.out.println("code is: " + code);
}
private static String getSampleString() {
String sample = "<washCode><getCode><code>12345</code></getCode></washCode>";
return sample;
}
}
答案 0 :(得分:1)
public String getAuthCodeResponse(String message) throws SAXException, IOException, ParserConfigurationException {
factory = SAXParserFactory.newInstance();
handler = new SAXParserUsage(); // <--- You create local instance here
parser = factory.newSAXParser();
parser.parse(new InputSource(new StringReader(message)), handler);
// ^^ parser writes to local instance here but ...
return authorizationCode;
// you return authCode field of the instance that this method is invoked on,
// which has not been changed by this method.
// So if it was null before, it still is null.
}
因此,您必须return handler.authorizationCode
或parser.parse(..., this);
答案 1 :(得分:1)
另请注意,您不能单独将一个元素的内容依赖于characters()方法。它可以分割为characters()方法的多个调用。这种情况不会经常发生 - 通常只有在文本包含实体引用或者它跨越两个I / O缓冲区之间的边界时才会发生 - 但事实上它很少会使这个bug非常隐蔽。您需要通过多次调用缓冲内容,并在执行endElement()事件时保存它。
您的代码中还有另一个技术错误,即如果解析器的http://xml.org/sax/features/namespace-prefixes属性的默认值为“false”,则解析器没有义务向startElement()提供qName参数。但是,我从未遇到过无法提供此参数的解析器,因此在实践中这个不太可能会打击你。
答案 2 :(得分:0)
尝试返回
handler.authorizationCode;
而不是
return authorizationCode;