要解析 SC_REPLY XML 消息(CRNP 服务器发送的响应注册或取消注册消息),需要使用 RegReply 帮助器类。可以从 XML 文档构造此类。此类提供了状态代码和状态消息的访问程序。要解析来自服务器的 XML 流,需要创建新的 XML 文档并使用该文档的解析方法。http://java.sun.com/xml/jaxp/index.html 中的 JAXP 文档详细介绍了此方法。
创建实现上述逻辑的 Java 代码。
请注意,readRegistrationReply 方法使用新的 RegReply 类。
private void readRegistrationReply(InputStream stream) throws Exception
{
// Create the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
//parse the input file
Document doc = db.parse(stream);
RegReply reply = new RegReply(doc);
reply.print(System.out);
}
实现 RegReply 类。
请注意,retrieveValues 方法将检索 XML 文档中的 DOM 树,并提取状态代码和状态消息。http://java.sun.com/xml/jaxp/index.html 中的 JAXP 文档包含详细说明。
class RegReply
{
public RegReply(Document doc)
{
retrieveValues(doc);
}
public String getStatusCode()
{
return (statusCode);
}
public String getStatusMsg()
{
return (statusMsg);
}
public void print(PrintStream out)
{
out.println(statusCode + ": " +
(statusMsg != null ? statusMsg : ""));
}
private void retrieveValues(Document doc)
{
Node n;
NodeList nl;
String nodeName;
// Find the SC_REPLY element.
nl = doc.getElementsByTagName("SC_REPLY");
if (nl.getLength() != 1) {
System.out.println("Error in parsing: can't find "
+ "SC_REPLY node.");
return;
}
n = nl.item(0);
// Retrieve the value of the statusCode attribute
statusCode = ((Element)n).getAttribute("STATUS_CODE");
// Find the SC_STATUS_MSG element
nl = ((Element)n).getElementsByTagName("SC_STATUS_MSG");
if (nl.getLength() != 1) {
System.out.println("Error in parsing: can't find "
+ "SC_STATUS_MSG node.");
return;
}
// Get the TEXT section, if there is one.
n = nl.item(0).getFirstChild();
if (n == null || n.getNodeType() != Node.TEXT_NODE) {
// Not an error if there isn't one, so we just silently return.
return;
}
// Retrieve the value
statusMsg = n.getNodeValue();
}
private String statusCode;
private String statusMsg;
}