Get elements by tag name from a Node document in Android (XML)?

I have an XML like this:

  <!--...-->
  <Cell X="4" Y="2" CellType="Magnet">
    <Direction>180</Direction>
    <SwitchOn>true</SwitchOn>
    <Color>-65536</Color>
  </Cell>
  <!--...-->

There are many Cell elements, and I can get the nodes of the cells GetElementsByTagName. However, I understand that the class Nodedoes NOT have a method GetElementsByTagName! How can I get a Directionnode from this node cell without going to the list ChildNodes? Can I get NodeListby tag name, for example, from a class Document?

Thank.

+5
source share
1 answer

NodeList Element, getElementsByTagName(); Element. - Cell Object , Direction, Switch, Color. .

String direction [];
NodeList cell = document.getElementsByTagName("Cell");
int length = cell.getLength();
direction = new String [length];
for (int i = 0; i < length; i++)
{
    Element element = (Element) cell.item(i);
    NodeList direction = element.getElementsByTagName("Direction");

    Element line = (Element) direction.item(0);

    direction [i] = getCharacterDataFromElement(line);

    // remaining elements e.g Switch , Color if needed
}

getCharacterDataFromElement() .

public static String getCharacterDataFromElement(Element e)
{
    Node child = e.getFirstChild();
    if (child instanceof CharacterData)
    {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
    }
    return "";
}
+13

All Articles