我有这样的
XML:
<!--...-->
<Cell X="4" Y="2" CellType="Magnet">
<Direction>180</Direction>
<SwitchOn>true</SwitchOn>
<Color>-65536</Color>
</Cell>
<!--...-->
有很多Cell元素,我可以通过GetElementsByTagName获取Cell Nodes.但是,我意识到Node类没有GetElementsByTagName方法!如何在不通过ChildNodes列表的情况下从该单元节点获取Direction节点?我可以通过标记名来获取NodeList吗?
谢谢.
解决方法
您可以使用Element再次强制转换NodeList项,然后使用getElementsByTagName();来自Element类.
最好的方法是在项目中创建一个Cell对象,以及Direction,Switch,Color等字段.然后得到这样的数据.
最好的方法是在项目中创建一个Cell对象,以及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 "";
}