开发者

Parse XML by referenceing parent node by using a variable

I am trying to use a var开发者_运维知识库iable that specifies which parent.child nodes I am parsing.

below is my current 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>

And here is my parsing code. I want to use the variable items to tell which node I am supposed to parse GW or 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);            
}

I am trying to only parse either the child nodes of GW or BF and that depends on the value of ITEMS. So if items is equal to 0 then I would get the data from GW and if it is 1 I would get the data from BF.

If I could guess it would be something like:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜