簡體   English   中英

在Android中使用SAXParser訪問XML中的子節點

[英]Accessing the child node in XML using SAXParser in android

我的XML樹具有以下結構:

<building id="5" name="Barracks" hp="2000" >
    <cost metal="100" wood = "300"></cost>
    <unit id="1" name="Swordsman" hp="40" attack="3"/>
    <tech id="1" name="Research Heavy Swordsman"/>
</building>

這是我用來訪問它的代碼:

public void startElement(String uri, String localName,String qName, 
                    Attributes attributes) throws SAXException {
            int civId=0, id=0;
            if(qName.equalsIgnoreCase("building"))
            {
                inBuilding = true;
                building = true;
                //Fetching the ID of TownCenter, we use it as a reference to fetch the child nodes.
                id = Integer.parseInt(attributes.getValue("id"));
                if(id==5)
                {
                    XMLfetch.put("id", attributes.getValue("id"));
                    XMLfetch.put("name", attributes.getValue("name"));
                    XMLfetch.put("hp", attributes.getValue("hp"));
                    ......
                }               
            }
            if(inBuilding && id==5){ //<----- Condition which matters
                if(qName.equalsIgnoreCase("cost")){

                    Log.i("resources", "Wood "+attributes.getValue("wood"));
                    Log.i("resources", "MetaL "+attributes.getValue("metal"));

                    XMLfetch.put("costWood", attributes.getValue("wood"));
                    XMLfetch.put("costMetal", attributes.getValue("stone"));

                }               
            }
        }

        // END ELEMENT here     
                @Override
                 public void endElement(String uri, String localName, String qName) throws SAXException {

                    if(inBuilding)
                    {
                        if(qName.equalsIgnoreCase("building")) {
                              building=false;
                              //inBuilding=false;
                              }
                        if(qName.equalsIgnoreCase("cost")){
                            inBuilding=false;
                        }
                    }

                 }

現在的問題是,我無法進入標簽內。 我無法訪問其屬性,什么也沒有。 如果我從上面提到的行中刪除“ id == 5”的條件,那么代碼將從整個樹中獲取所有cost值。 但是,當我提出條件時,它什么也收不到! :( ...

請幫忙。 非常感謝!

解決了! 我在錯誤的地方聲明了inBuilding變量。 :( ....因此,變量被重寫,我無法檢測到我在哪里。盡管感謝所有閱讀它並嘗試給出解決方案的人。:) civId和id變量在startElement( ),這意味着它們每次都會被重寫。...因此,它們是無用的。 需要在不會被重寫的任何地方聲明它們。 謝謝ianhanniballake

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM