XML parsing working fine with Android 2.2, 2.3 but

2019-03-03 02:25发布

问题:

I am fetching the some data from the server using XML parsing that is not working with ICS version of Android.here is my please tell me what correction do I make so that I should also run on ICS...(It's working fine with lower versions). Here is my code

try {
        URL url = new URL(
                "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("file");

        namephoto = new String[nodeList.getLength()];
        for (int i = 0; i < nodeList.getLength(); i++) {

            Node node = nodeList.item(i);
            Element fstElmnt = (Element) node;
            NodeList nameList = fstElmnt.getElementsByTagName("file");
            Element nameElement = (Element) nameList.item(0);
            nameList = nameElement.getChildNodes();
            namephoto[i] = ((Node) nameList.item(0)).getNodeValue();

        }
    } catch (Exception e) {
        Log.e("name", "" + e);
    }
    photobitmap = new Bitmap[namephoto.length];

    setPhotoBackground(namephoto[index_photo]);

My XML code like this.

<?xml version="1.0"?>
-<root><file>1 a.JPG</file><file>2 b.JPG</file><file>3 c.JPG</file><file>4 d.JPG</file>  </root>

回答1:

i have got the solution myself.. Here is the code which is compatible with Android 4.0 as well as rest of the android versions...Just change the for loop like this.

for (int i = 0; i < nodeList.getLength(); i++) {
            Node name = nodeList.item(i);
            NodeList nodeEle = name.getChildNodes();
            namephoto[i] = ((Node) nodeEle.item(0)).getNodeValue();

        }