Get Elements by Tag Name from a Node in Android (XML) Document?

12,975

You can cast the NodeList item again with Element and then use getElementsByTagName(); from Element class. The best approach is to make a Cell Object in your project alongwith fields like Direction, Switch, Color. Then get your data something like this.

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
}

Where your getCharacterDataFromElement() will be as follow.

public static String getCharacterDataFromElement(Element e)
{
    Node child = e.getFirstChild();
    if (child instanceof CharacterData)
    {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
    }
    return "";
}
Share:
12,975
Luke Vo
Author by

Luke Vo

Updated on June 07, 2022

Comments

  • Luke Vo
    Luke Vo almost 2 years

    I have an XML like this:

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

    There're many Cell elements, and I can get the Cell Nodes by GetElementsByTagName. However, I realise that Node class DOESN'T have GetElementsByTagName method! How can I get Direction node from that cell node, without go throught the list of ChildNodes? Can I get the NodeList by Tag name like from Document class?

    Thank you.

  • Luke Vo
    Luke Vo almost 13 years
    Thanks, I forgot Node can be cast to Element! Happy coding :)