我有这样一个 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
节点?我可以像 Document
类一样通过标签名称获取 NodeList
吗?
谢谢。
最佳答案
您可以使用 Element
再次转换 NodeList
项,然后使用 Element
类中的 getElementsByTagName();
.
最好的方法是在您的项目中创建一个 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 "";
}
关于android - 从 Android (XML) 文档中的节点按标签名称获取元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6381076/