从Android(XML)文档中的节点获取标签名称元素?

前端之家收集整理的这篇文章主要介绍了从Android(XML)文档中的节点获取标签名称元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这样的 XML: @H_502_2@<!--...--> <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等字段.然后得到这样的数据. @H_502_2@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()将如下所示.

@H_502_2@public static String getCharacterDataFromElement(Element e) { Node child = e.getFirstChild(); if (child instanceof CharacterData) { CharacterData cd = (CharacterData) child; return cd.getData(); } return ""; }

猜你在找的Android相关文章