【问题标题】:Get specific XML tag text using Java in Android app在 Android 应用中使用 Java 获取特定的 XML 标记文本
【发布时间】:2012-05-29 17:30:15
【问题描述】:

我一直在尝试使用 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”数字拉取它们,而不必设置我自己的对象。如果可能的话。

【问题讨论】:

    标签: java android xml parsing


    【解决方案1】:

    您可以使用此代码:

            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();
    

    【讨论】:

    • 这很接近,但我希望能够使用 ID 作为标识符(如主键)来提取可能不是第一个特定“故事”的所有数据。
    • 我最终不得不将其移动到对象中以完成我想要完成的工作,但这回答了基本问题。如果将来有人遇到这样的问题,您将不得不将您的 XML 解组为对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    相关资源
    最近更新 更多