How do I get the tag 'Name' from a XML Node in Java (Android)

I have a tiny little problem parsing an XML file in Java (Android).

I have an XML file that is like this:

<Events>
  <Event Name="Olympus Has Fallen">
    ...
  </Event>
  <Event Name="Iron Man 3">
    ...
  </Event>
</Events>

I already managed to get the NodeList by doing this:

URL url = new URL("********");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("Event");

Also I managed to get every single item of the NodeList by doing this:

for (int i = 0; i < nodeList.getLength(); i++) {
    // Item
    Node node = nodeList.item(i);
    Log.i("film", node.getNodeName());
}

But this just Logs: "Event" instead of the value of the Name tag. How do I output the value of this 'name' tag from the XML.

Can anyone help me with this one? Thanks in advance!

Upvotes: 1

Views: 7545

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500515

But this just Logs: "Event" instead of the value of the Name tag.

Yes, because you're asking for the name of the element. There isn't a Name "tag" - there's a Name attribute, and that's what you should find:

// Only check in elements, and only those which actually have attributes.
if (node.hasAttributes()) {
    NamedNodeMap attributes = node.getAttributes();
    Node nameAttribute = attributes.getNamedItem("Name");
    if (nameAttribute != null) {
        System.out.println("Name attribute: " + nameAttribute.getTextContent());
    }
}

(It's very important to be precise in terminology - it's worth knowing the difference between nodes, elements, attributes etc. It will help you enormously both when communicating with others and when looking for the right bits of API to call.)

Upvotes: 6

Related Questions