我正在使用 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;
}
}
最佳答案
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);
关于java - 使用 SAXParser 从对象返回 Null - NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25673604/