【问题标题】:Android: How to get the value of a TAG: with XmlPullParserAndroid:如何获取 TAG 的值:使用 XmlPullParser
【发布时间】:2020-11-01 06:31:51
【问题描述】:

如标题所述,使用 XmlPullParser,可以获取 XML 文档的标签,其函数如下所示:

  public static void parseXML(Context context) {
        XmlPullParserFactory parserFactory;
        try {
            parserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = parserFactory.newPullParser();
            InputStream is = context.getAssets().open("example.xml");
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(is, null);

            processParsing(parser);

        } catch (XmlPullParserException e) {

        } catch (IOException e) {
        }
}

public static void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String eltName = null;

            switch (eventType) {
                case XmlPullParser.START_TAG:
                    eltName = parser.getName();

                    System.out.println(eltName); //Delievers the TAG-Name
                    System.out.println(parser.getText()); // Should deliever the TAG-Value - delievers 'null'
                    System.out.println(parser.nextText()); // Also doesn't give out any value.

                    break;
            }
            eventType = parser.next();
        }
    }

XML:example.xml

<players>
    <player>
        <name>Lebron James</name>
        <age>32</age>
        <position>SF/PF</position>
    </player>
    <player>
        <name>Kevin Durant</name>
        <age>29</age>
        <position>SF/PF</position>
    </player>
    <player>
        <name>Stephen Curry</name>
        <age>29</age>
        <position>PG</position>
    </player>
</players>

问题: System.out.println(parser.getText()); // 应该传递 TAG-Value - delievers 'null' System.out.println(parser.nextText()); // 也不给出任何值。

问题:如何获取给定 XML-Document 中标签的值?

如何获得价值

【问题讨论】:

    标签: android xml android-studio parsing xmlpullparser


    【解决方案1】:

    为了获取文本,你需要在这里有另一个案例:

    案例 XmlPullParser.TEXT:

    然后在该块中,您可以获取文本。

    parser.getText()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多