通过使用变量引用父节点来解析XML

时间:2011-06-22 02:55:03

标签: java android xml

我正在尝试使用一个变量来指定我正在解析哪个parent.child个节点。

下面是我当前的xml:

<results>
    <GW>
            <result>
                     <item>Car</item>
                     <name>Bob</name
            </result>
            <result>
                     <item>Bike</item>
                     <name>Tom</name
            </result>
    </GW>

    <BF>
            <result>
                     <item>Apple</item>
                     <name>Mike</name
            </result>
            <result>
                     <item>Melon</item>
                     <name>Julia</name
            </result>
    </BF>


</results>

这是我的解析代码。我想使用变量items来告诉我应该解析哪个节点GW或BF

//DOC IS ASSIGNED THE XML DATA EARLIER IN THE CODE

 Bundle bundle = getIntent().getExtras();
 int ITEMS = bundle.getInt("selection");


NodeList nodes = doc.node[ITEMS].getElementsByTagName("result");

for (int i = 0; i < nodes.getLength(); i++) {
    HashMap<String, String> map = new HashMap<String, String>();    

    Element e = (Element)nodes.item(i);
    map.put("main_content", XMLfunctions.getValue(e, "item"));
    map.put("name", XMLfunctions.getValue(e, "name"));
    mylist.add(map);            
}

我试图只解析GW或BF的子节点,这取决于ITEMS的值。因此,如果items等于0,那么我将从GW获取数据,如果它是1,我将从BF获取数据。

如果我能猜到它会是这样的:

NodeList nodes = doc.childNode[ITEMS].getElementsByTagName("result");

1 个答案:

答案 0 :(得分:1)

Element docElem = doc.getDocumentElement();
NodeList nl = docElem.getElementsByTagName("results");
Element elem = (Element)nl.item(ITEMS);
nodes = elem.getElementsByTagName("result");