【发布时间】:2014-09-04 19:30:09
【问题描述】:
我正在使用 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;
}
}
【问题讨论】:
-
试试
return handler.authorizationCode -
@NathanHughes 方法 getAuthCodeResponse 正在返回
Null,而我在解析期间设置了 authorizationCode 的值 -
@Fildor 谢谢它的工作。
-
@Fildor 请您回答同样的问题并给出一些解释