Search code examples
androidxmldomparser

How to parse <img src="value" from this XML by using DOM?


It look like this in XML. I want to get he Image src value...

<description><![CDATA[<div class="images"><img src="http://www.voicetv.co.th/cache/images/8a1a6f2aeb7b0e9c1d6bb3eae314165f.jpg" /></div>]]></description>

What I am doing is

if ((theElement.getElementsByTagName("description")).getLength() > 0) {

            allChildern = theElement.getElementsByTagName("description").item(0).getChildNodes();

            for (int index = 0; index < allChildern.getLength(); index++) {
                description += allChildern.item(index).getNodeValue();

                NodeList chNodes = allChildern.item(index).getChildNodes();
                for (int i = 0; i < chNodes.getLength(); i++) {

                    String name = chNodes.item(i).getNodeName();
                    if(name.equals("div")) {
                        String clas = allChildern.item(index).getAttributes().getNamedItem("class").getNodeValue();
                        if(clas.equals("images")){
                            String nName = allChildern.item(index).getChildNodes().item(0).getNodeName();
                            if(nName.equals("img")) {
                                String nValue = allChildern.item(index).getChildNodes().item(0).getAttributes().getNamedItem("src").getNodeValue();
                            }
                        }
                    }
                }


            }
            currentStory.setDescription(description);
        }

But is is not working


Solution

  • The description element contains a CDATA node. This means that the <img> "element" you are trying to access is really just a piece of text (and not an element at all).

    You'll need to parse the text as a new XML document in order to access it via DOM methods.