libgdx XML访问孩子里面的孩子

时间:2016-06-26 18:41:36

标签: xml libgdx

我有一个像这样的xml文件:

<main>
    <zone id="A1">
        <area id="house">
            <sprite>test.jpg</sprite>
            <location x="33" y="345"/>
            <sprite>test.jpg</sprite>
            <location x="33" y="345"/>
            <text id="1">text example</text>
            <text id="2">text example</text>
            <text id="3">text example</text>
            <text id="4">text example</text>
            <text id="5">text example</text>
            <text id="6">text example</text>
            <text id="7">text example</text>
            <text id="8">text example</text>
            <text id="9">text example</text>
            <text id="10">text example</text>
        </area>
    </zone>
    <zone id="A2">
        <area id="house">
            <sprite>test2.jpg</sprite>
            <location x="32" y="11"/>
            <text id="1">text example</text>
            <text id="2">text example</text>
            <text id="3">text example</text>
        </area>
    </zone>
</main>

我有 main 作为根元素,2个子元素称为区域,具有不同的id并且在zone元素内部还有另一个名为 area 有不同的身份证。我想要读取的所有数据都在area元素内。 我需要创建一个带有两个参数zoneIdareaId的函数来读取特定的区域信息并将其作为数组或对象返回。

1 个答案:

答案 0 :(得分:0)

以下是您的问题的解决方案:

private void readXml(String zoneToFind, String areaToFind) {
    XmlReader reader = new XmlReader();
    try {
        XmlReader.Element root = reader.parse(Gdx.files.internal("test.xml"));
        Array<XmlReader.Element> zones = root.getChildrenByName("zone");
        for (XmlReader.Element zone : zones) {
            if (zoneToFind.equals(zone.getAttribute("id"))) {
                Array<XmlReader.Element> areas = zone.getChildrenByName("area");
                for (XmlReader.Element area : areas) {
                    if (areaToFind.equals(area.getAttribute("id"))) {
                        for (int i = 0; i < area.getChildCount(); i++) {
                            XmlReader.Element child = area.getChild(i);
                            child.getName();
                            child.getText();
                            child.getAttributes();

                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        // proper exception handling
    }

}

说明:

  1. 首先,您应该通过

    获取xml文件的根目录

    XmlReader.Element root = reader.parse(Gdx.files.internal(“test.xml”));

  2. test.xml应位于Android资源文件夹

    1. 然后,您遍历所有区域的子项,直到找到匹配项。当找到匹配时,我们知道我们得到的下一个元素是区域,所以我们再次迭代,直到找到与区域的匹配。
    2. 请注意,如果没有匹配,您应该正确处理这些情况。

      1. 最后,我们知道当前区域正是我们所寻找的,因此您可以遍历其所有子项并执行您需要的任何操作。但是这三种方法应该返回有关元素的足够信息:

        child.getName(); -- name is like sprite, location... 
        child.getText(); -- text is like text example... 
        child.getAttributes(); - attributes are id, x, y...