1

我正在创建一个帮助方法,该方法允许我遍历 XML 文档并将每个元素放入数据 HashMap 中,然后返回它。这是我一直在研究的方法:

private static HashMap<String, String> traverseNodes( Node n, HashMap<String,String> data ) 
{
    NodeList children = n.getChildNodes();
    if( children != null ) {
      for( int i = 0; i < children.getLength(); i++ ) {
        Node childNode = children.item( i );

        String nodeName = childNode.getNodeName();
        if(childNode instanceof Element)
        {
            data.put(nodeName, getStringByTag(nodeName, (Element)childNode));
            Log.d("traversal", childNode.getNodeName() + " was saved in hashmap");
        }


        else
            Log.d("traversal", childNode.getNodeName() + " Is not an Element type");

        System.out.println( "node name = " + childNode.getNodeName() );
        traverseNodes( childNode, data );
      }
    }

    return data;

}

我尝试运行该示例,虽然我收到消息说“childNode.getNodeName() +”已保存在 hashmap 中。但返回的 HashMap 是空的。

我究竟做错了什么?

编辑!奖励问题:我编辑了代码以反映建议的更改。然而,似乎该方法本身并没有保存我的 XML 文档的值。方法的逻辑有问题吗?

4

4 回答 4

4

您正在为每次通话创建一个新地图。您需要将现有地图传递给递归调用。它应该看起来像这样:

private static Map<String, String> traverseNodes(Node n) {
    Map<String, String> map = new HashMap<String, String>();
    traverseNodesRecurse(n, map);
    return map;
}

private static void traverseNodesRecurse(Node n, Map<String, String> map) {
    // Logic as per question
    // Recursive call (in the loop, etc)
    traverseNodes(childNode, map);

    // No need for a return statement
}
于 2012-06-21T06:37:16.360 回答
0

I think you need something like that

private static HashMap<String, String> traverseNodes( Node n ) {
    HashMap<String, String> data = new HashMap<String, String>();
    traverseNodes( n, data );
    return data;
}

private static void traverseNodes( Node n, HashMap<String, String> data ) {
    // Here is your recursive code that do data.put(key, value)
}
于 2012-06-21T06:41:18.940 回答
0
private static HashMap<String, String> data = new HashMap<String, String>();

private static traverseNodes( Node n) 
{
    NodeList children = n.getChildNodes();
    if( children != null ) {
      for( int i = 0; i < children.getLength(); i++ ) {


        Node childNode = children.item( i );

        if(childNode instanceof Element)
        {

            String nodeName = childNode.getNodeName();
            data.put(nodeName, getStringByTag(nodeName, (Element)childNode));
            Log.d("traversal", childNode.getNodeName() + " was saved in hashmap");
        }


        else
            Log.d("traversal", childNode.getNodeName() + " Is not an Element type");

        System.out.println( "node name = " + childNode.getNodeName() );
        traverseNodes( childNode);
      }
    }

    return data;

}
于 2012-06-21T07:22:42.960 回答
0

我会说保持HashMap在方法之外并将其作为参数传递 -

private static HashMap<String, String> traverseNodes( Node n, HashMap<String, String> data  ) 
于 2012-06-21T06:37:41.297 回答