开发者

why does getTagValue throws nullpointer if empty

开发者 https://www.devze.com 2023-03-03 03:46 出处:网络
I am parsing a xmlfile on android and I have something similar to: <images> <image></image>

I am parsing a xmlfile on android and I have something similar to:

<images>
 <image></image>
</images>

I have the following code:

Element imagesElement = (Element) poiElement.getElementsByTagName("images").item(0);
                        NodeList images = imagesElement.getElementsByTagName("image");
                        for (int n = 0; n < images.getLength(); n++) {
                            Element imgElement = (Element) images.item(n);
                            String imgUrl = getTagValue("image", imgElement);<< ERROR HERE
                            if (imgUrl != "") {
                        开发者_运维百科        //do something here                             }
                        }

If I run the getTagValue("image",imgElement) when the tag is empty I get a null pointer exception, if I run it when there is something in it it returns the value. I'd expect an empty string if it was empty!

I've tried examining the imgElement in eclipses debugger to try and determine how I check if it's empty but I can't work out how! Can anyone help?

Bex


It would appear that Element imgElement = (Element) images.item(n); is returning null. You could encapsulate the code following that statement in an if (imgElement != null) to stop the exception.

As a side note, if you are just reading data from the XML and not changing it, you are better off using the SAXParser rather than the DocumentBuilder class.


I have worked out what I need to do;

Element imgElement = (Element) images.item(n);
NodeList fstNm = imgElement.getChildNodes();  //<--- Get the child nodes of the image element
Node Test = ((Node) fstNm.item(0)); //<---- check that the child node isn't null, 
I don't understand why node, but it works!
0

精彩评论

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