Get Elements by Tag Name from a Node in Android (XML) Document?
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 c开发者_JAVA技巧an 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.
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 "";
}
加载中,请稍侯......
精彩评论