【问题标题】:Get Elements by Tag Name from a Node in Android (XML) Document?从Android(XML)文档中的节点按标签名称获取元素?
【发布时间】:2011-09-16 21:18:15
【问题描述】:

我有一个这样的 XML:

  <!--...-->
  <Cell X="4" Y="2" CellType="Magnet">
    <Direction>180</Direction>
    <SwitchOn>true</SwitchOn>
    <Color>-65536</Color>
  </Cell>
  <!--...-->

Cell elements 很多,我可以通过GetElementsByTagName 获取单元节点。但是,我意识到 Node 类没有 GetElementsByTagName 方法!我怎样才能从该单元节点获取Direction 节点,而不通过ChildNodes 的列表?我可以从Document 类中通过标签名称获取NodeList 吗?

谢谢。

【问题讨论】:

    标签: android xml xml-parsing


    【解决方案1】:

    您可以使用Element 再次投射NodeList 项目,然后使用Element 类中的getElementsByTagName();。 最好的方法是在您的项目中创建一个Cell Object 以及DirectionSwitchColor 等字段。然后像这样获取您的数据。

    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 "";
    }
    

    【讨论】:

    • 谢谢,我忘了 Node 可以转换为 Element!快乐编码:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多