<?xml version="1.0"?><myStuff>
<paul atrA="46" atrB="10457152"><TEST>hellothere</TEST>
</paul>
</myStuff>
我可以从TEST中包含的信息中提取所有内容。我需要获取TEST中包含的信息。我该怎么做?
到目前为止,这是我的代码:
private Map<String, String> parseResponse(final String responseXml) throws IOException, ParserConfigurationException, SAXException {
System.out.println(responseXml);
Document doc = parseXml(responseXml);
return extractAttributes(doc);
}
private Map<String, String> extractAttributes(Document doc) {
NodeList nList = doc.getElementsByTagName("paul");
Map<String, String> keyValues = new HashMap<String, String>();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NamedNodeMap attrs = eElement.getAttributes();
int len = attrs.getLength();
for (int i = 0; i < len; i++) {
Attr attr = (Attr) attrs.item(i);
keyValues.put(attr.getNodeName(), attr.getNodeValue());
}
}
}
return keyValues;
}
答案 0 :(得分:0)
您的<TEST>
节点是<paul>
的子节点,因此您必须执行getChildNodes(),然后迭代它们。
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// iterate through children here.
NodeList childrenList = eElement.getChildNodes();
for ( Node aNode : childrenList ) {
// YOU SHOULD HAVE TEST HERE
}
NamedNodeMap attrs = eElement.getAttributes();
int len = attrs.getLength();
for (int i = 0; i < len; i++) {
Attr attr = (Attr) attrs.item(i);
keyValues.put(attr.getNodeName(), attr.getNodeValue());
}
}
}