Java DOM XML子节点

时间:2011-06-14 23:56:34

标签: java xml dom

经过几个小时尝试各种各样的事情后,我感到困惑和沮丧(可能是它的压力使我的能力蒙上阴影)。我的XM字符串如下所示:

<?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;
}

1 个答案:

答案 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());
        }

    }
}