Search code examples
androidxmlgdata

Android parse XML to get node value


So, I have written something small to parse the feed for a Youtube user.

The problem is that when I call getNodeValue() null is returned. Why is this? Any ideas or alternative approached appreciated, thanks.

Here's a snippet of how i'm currently doing things:

try {

    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("https://gdata.youtube.com/feeds/api/users/estudiosabiertostv/uploads");

    NodeList entries = d.getElementsByTagName("entry");

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

        NodeList children = entries.item(i).getChildNodes();
        YoutubeVideo video = new YoutubeVideo();

        for(int j = 0; j < children.getLength(); j++) {

            Node child = children.item(j);

            if(child.getNodeName().equals("title")) {

                video.title = child.getNodeValue();
                break;
            }
        }
        videos.add(video);
    }
}
catch (Exception e) {

    e.printStackTrace();
}

Here is the url where I am getting the XML from:

https://gdata.youtube.com/feeds/api/users/estudiosabiertostv/uploads

Here's a snippet of an entry, of which I am trying to get the title

<entry>
    <id>http://gdata.youtube.com/feeds/api/videos/oDbOmTY3gDw</id>
    <published>2012-12-17T08:14:12.000Z</published>
    <category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video"/>
    <title type="text">SEAS - Grupo San Valero - Crea tu propia Navidad (2012)</title>

    <content type="text">Felicitación de Navidad de SEAS, Estudios Abiertos del Grupo San Valero</content>
    <link rel="alternate" type="text/html" href="http://www.youtube.com/watch?v=oDbOmTY3gDw&feature=youtube_gdata"/>
    <author>
        <name>estudiosabiertostv</name>
        <uri>http://gdata.youtube.com/feeds/api/users/estudiosabiertostv</uri>
    </author>
</entry>

Solution

  • The title node should in turn have a child - a text node, and that one should contain the actual text.

    Also, beware of fragmentation: there may be several adjacent text nodes there, as discussed here: http://www.drillio.com/en/software-development/java/fragmented-xml-text-nodes/