Android解析plist字符串和整数

时间:2012-09-02 10:10:11

标签: android parsing plist

嗨我正在尝试解析android中的plist我使用的是http://kpbird.blogspot.co.uk/2011/08/android-plist-parser.html

中使用的KPBirds plist解析器的修改版本

问题是我设置的所有内容都没有错误,但是当我运行它时,它试图通过整数解析字符串。例如:name被设置为一个字符串,它通过说name不能被解析为整数。

关于为什么的任何想法?

到目前为止,我的代码工作方式是在我的活动中运行一个函数,它获取plist的读取然后将数据模型应用于它,然后将其记录在log cat中。

继承错误

09-02 10:49:44.717: E/AndroidRuntime(1736): Caused by: java.lang.NumberFormatException: unable to parse 'image1' as integer
09-02 10:49:44.717: E/AndroidRuntime(1736):     at java.lang.Integer.parse(Integer.java:383)
09-02 10:49:44.717: E/AndroidRuntime(1736):     at java.lang.Integer.parseInt(Integer.java:372)
09-02 10:49:44.717: E/AndroidRuntime(1736):     at java.lang.Integer.parseInt(Integer.java:332)
09-02 10:49:44.717: E/AndroidRuntime(1736):     at co.uk.luke.ParsePlist.parsePlist(ParsePlist.java:68)
09-02 10:49:44.717: E/AndroidRuntime(1736):     at co.uk.luke.LevelSelect.readPlistContents(LevelSelect.java:63)
09-02 10:49:44.717: E/AndroidRuntime(1736):     at co.uk.luke.LevelSelect.onCreate(LevelSelect.java:91)
09-02 10:49:44.717: E/AndroidRuntime(1736):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
09-02 10:49:44.717: E/AndroidRuntime(1736):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1785)

继承我的活动,我称之为功能

/// Read plist from Assets
        private String readPlistFromAssets() {
            StringBuffer sb = new StringBuffer();
            BufferedReader br=null;
            try {
                 br = new BufferedReader(new InputStreamReader(getAssets().open("Levels.plist"))); 
                String temp;
                while ((temp = br.readLine()) != null)
                    sb.append(temp);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close(); // stop reading
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            return sb.toString();
        }


        public void readPlistContents(){
            // Read Plist content
            String xml = readPlistFromAssets();
            // create object of Parser Class
            ParsePlist pp = new ParsePlist();
            // parse Plist and fill in plist array
            ArrayList<DataModel> plist = pp.parsePlist(xml);
            // Print ArrayList
            Iterator<DataModel> i = plist.iterator();
            while(i.hasNext()){
                DataModel d = i.next();
                Log.i("Plist","=========================");
                Log.i("Plist","Levelid = " + d.getLevelid());
                Log.i("Plist","title = " + d.getTitle());
                Log.i("Plist","name = " + d.getName());
                Log.i("Plist","lockStatus = " + d.getLockStatus());
                Log.i("Plist","total = " + d.getTotal());
                Log.i("Plist","totalCompleted = " + d.getTotalCompleted());
                Log.i("Plist","Points = " + d.getPoints());
                Log.i("Plist","Image = " + d.getImage());

            }
            Toast.makeText(this, "Parsing completed please check logcat...", Toast.LENGTH_LONG).show();

        }

继承我的数据模型

public class DataModel {

    private String title;
    private String name;
    private String levelid;
    private String lockStatus;
    private int total;
    private int totalCompleted;
    private int Points;
    private String Image;


    public int getTotaCompleted() {
        return totalCompleted;
    }
    public void setTotalCompleted(int totalCompleted) {
        this.totalCompleted = totalCompleted;
    }

    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }

    public int getPoints() {
        return Points;
    }
    public void setPoints(int Points) {
        this.Points = Points;
    }



    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLevelid() {
        return levelid;
    }
    public void setLevelid(String levelid) {
        this.levelid = levelid;
    }
    public String getLockStatus() {
        return lockStatus;
    }
    public void setLockStatus(String lockStatus) {
        this.lockStatus = lockStatus;
    }

    public String getImage() {
        return Image;
    }
    public void setImage(String Image) {
        this.Image = Image;
    }


}

继承我解析plist的代码

public class ParsePlist {


    // parse Plist and fill in arraylist
    public ArrayList<DataModel> parsePlist(String xml) {
        final ArrayList<DataModel> dataModels = new ArrayList<DataModel>();
        //Get the xml string from assets

        final Document doc = XMLfromString(xml);

        final NodeList nodes_array = doc.getElementsByTagName("array");

        //Fill in the list items from the XML document
        for ( int index = 0; index < nodes_array.getLength(); index++ ) {

            final Node node = nodes_array.item(index);

            if ( node.getNodeType() == Node.ELEMENT_NODE ) {
                final Element e = (Element)nodes_array.item(index);

                final NodeList nodeKey = e.getElementsByTagName("key");
                final NodeList nodeString = e.getElementsByTagName("string");
                DataModel model = new DataModel();

                for (int i=0; i<nodeString.getLength(); i++) {

                    final Element eleKey = (Element)nodeKey.item(i);
                    final Element eleString = (Element)nodeString.item(i);


                    if ( eleString != null ) {

                        String strValue = getValue(eleString, "string");


                        if(getValue(eleKey, "key").equals("title")) {
                            model = new DataModel();
                            model.setTitle(strValue);

                        } else if(getValue(eleKey, "key").equals("name")) {
                            model.setName(strValue);

                        } else if(getValue(eleKey, "key").equals("levelid")) {
                            model.setLevelid(strValue); 


                        } else if(getValue(eleKey, "key").equals("lockStatus")) {
                            model.setLockStatus(strValue);  

                        } else if(getValue(eleKey, "key").equals("total")) {
                            model.setTotal(Integer.parseInt(strValue));

                        } else if(getValue(eleKey, "key").equals("totalCompleted")) {
                            model.setTotalCompleted(Integer.parseInt(strValue));


                        } else if(getValue(eleKey, "key").equals("Points")) {
                            model.setPoints(Integer.parseInt(strValue));

                        } else if(getValue(eleKey, "key").equals("Image")) {
                            model.setImage(strValue);   


                            dataModels.add(model);
                        }
                    }
                }
            }
        }
        return dataModels;
    }

    // Create xml document object from XML String
    private  Document XMLfromString(String xml) {
        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);
        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;
    }

    // fetch value from Text Node only
    private   String getElementValue(Node elem) {
        Node kid;
        if (elem != null) {
            if (elem.hasChildNodes()) {
                for (kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling()) {
                    if (kid.getNodeType() == Node.TEXT_NODE) {
                        return kid.getNodeValue();
                    }
                }
            }
        }
        return "";
    }

    /// Fetch value from XML Node
    private   String getValue(Element item, String str) {
        NodeList n = item.getElementsByTagName(str);
        return getElementValue(n.item(0));
    }
}

最后继承我的plist

<key>title</key>
        <string>ZONE1</string>
        <key>name</key>
        <string>LEVEL 1</string>
        <key>levelid</key>
        <string>1</string>
        <key>lockStatus</key>
        <string>UNLOCKED</string>
        <key>total</key>
        <integer>20</integer>
        <key>totalCompleted</key>
        <integer>0</integer>
        <key>Points</key>
        <integer>0</integer>
        <key>Image</key>
        <string>image1</string>

1 个答案:

答案 0 :(得分:0)

 final NodeList nodeKey = e.getElementsByTagName("key");
 final NodeList nodeString = e.getElementsByTagName("string");

添加

final NodeList nodeInteger = e.getElementsByTagName(“integer”);

在第二行for循环后添加

final Element eleString = (Element)nodeString.item(i);

 final Element eleInteger = (Element)nodeInteger .item(i);

然后检查另一个条件

if ( eleInteger != null ) {

 String strValue = getValue(eleInteger, "integer");

}