如果XML对象有一个唯一的内部标记,我就能够解析它。但是,当我在父标记中有两个重复标记时,问题就出现了。如何获得两个标记值?我将以XML字符串的形式获得响应。
这是我的密码
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(responseXML));
if (is != null) {
Document doc = db.parse(is);
String errorCode = "";
NodeList errorDetails = doc.getElementsByTagName("ERROR-LIST");
if (errorDetails != null) {
int length = errorDetails.getLength();
if (length > 0) {
for (int i = 0; i < length; i++) {
if (errorDetails.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) errorDetails.item(i);
if (el.getNodeName().contains("ERROR-LIST")) {
NodeList errorCodes = el.getElementsByTagName("ERROR-CODE");
for (int j = 0; j < errorCodes.getLength(); j++) {
Node errorCode1 = errorCodes.item(j);
logger.info(errorCode1.getNodeValue());
}
}
}
}
} else {
isValidResponse = true;
}
}
}我从服务器得到的响应是
<DATA><HEADER><RESPONSE-TYPE CODE = "0" DESCRIPTION = "Response Error" />
</HEADER><BODY><ERROR-LIST>
<ERROR-CODE>9000</ERROR-CODE>
<ERROR-CODE>1076</ERROR-CODE>
</ERROR-LIST></BODY></DATA>我只能得到9000错误代码,我如何才能捕获所有错误代码下的错误列表?
任何想法都将不胜感激。
发布于 2017-09-18 07:39:55
您正在显式地请求错误列表的第一个元素:
el.getElementsByTagName("ERROR-CODE").item(0).getTextContent();循环遍历所有节点,getElementsByTagName返回。
NodeList errorCodes = el.getElementsByTagName("ERROR-CODE");
for (int j = 0; j < errorCodes.getLength(); j++) {
String errorCode = errorCodes.item(j).getTextContent();
}https://stackoverflow.com/questions/46273975
复制相似问题