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 "";
}
Author by
Luke Vo
Updated on June 07, 2022Comments
-
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 byGetElementsByTagName
. However, I realise thatNode
class DOESN'T haveGetElementsByTagName
method! How can I getDirection
node from that cell node, without go throught the list ofChildNodes
? Can I get theNodeList
by Tag name like fromDocument
class?Thank you.
-
Luke Vo almost 13 yearsThanks, I forgot Node can be cast to Element! Happy coding :)