在Android应用中使用Java获取特定的XML标记文本

时间:2012-05-29 17:30:15

标签: java android xml parsing

我一直在尝试使用XmlResourceParser,但我觉得它不适合这项工作。我有一组包含子项目的项目,我想拉出一个特定项目,例如此列表中的第二项:

<story>
    <id>1</id>
    <name>The First Room</name>
    <description>You aren't sure how you ended up here, but there is nothing in this room of interest. You should probably escape.</description>
    <direction>
        <name>North</name>
        <id>2</id>
    </direction>
    <direction>
        <name>East</name>
        <id>3</id>
    </direction>
</story>
<story>
    <id>2</id>
    <name>Moldy Room</name>
    <description>This room is filled with mold. It would be hazardous to your heath to stick around here.</description>
    <direction>
        <name>South</name>
        <id>1</id>
    </direction>
    <direction>
        <name>West</name>
        <id>4</id>
    </direction>
</story>

我希望能够简单地通过“id”号码来提取它们,而无需设置我自己的对象。如果可能的话。

1 个答案:

答案 0 :(得分:0)

您可以使用此代码:

        Resources res = activity.getResources();
        XmlResourceParser xpp = res
                .getXml(R.xml.myxml);
        xpp.next();
        int eventType = xpp.getEventType();
        eventType = xpp.next();
        eventType = xpp.next();
        eventType = xpp.next();

        short id = Short
                .parseShort(xpp.getText());

        Toast.makeText(
                activity.getApplicationContext(),
                "" + id, Toast.LENGTH_LONG)
                .show();
相关问题