有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaXMLParser。getText()正在提供null

我试图从一个预设的xml文件中提取值,当我试图检查值是什么时,我总是得到空值

if (pulled.equals("preset")) {
    presetName = xmlParser.getAttributeValue(null,"name");
    Log.d(TAG, presetName + " = " + xmlParser.getText());
}

这是我从中提取值的xml

<?xml version="1.0" encoding="utf-8"?>
<sports>
    <sport name="Baseball" paid="false">
        <preset name="Pitching Mound">726.0</preset>
        <preset name="Base Distance">1080.0</preset>
    </sport>
    <sport name="Basketball" paid="false">
        <preset name="NBA Free Throw Line">181.08</preset>
        <preset name="NBA 3pt Line">265.8</preset>
    </sport>
    <sport name="Cricket" paid="true">
        <preset name="Cricket Pitch">2012.0</preset>
        <preset name="Testing">0.8</preset>
    </sport>
</sports>

我做错什么了吗


共 (1) 个答案

  1. # 1 楼答案

    在XmlPullParser api上,getText()方法具有以下描述:

    Returns the text content of the current event as String. The value returned depends on current event type, for example for TEXT event it is element content (this is typical case when next() is used). See description of nextToken() for detailed description of
    possible returned values for different types of events.

    NOTE: in case of ENTITY_REF, this method returns the entity replacement text (or null if not available). This is the only case where getText() and getTextCharacters() return different values.

    因此,基于此描述,首先必须检查当前xml节点是否为文本,以便getText()不返回null

    if (pulled.equals("preset")) {
        presetName = xmlParser.getAttributeValue(null,"name");
        if (xmlParser.getEventType() == XmlPullParser.TEXT) {
           Log.d(TAG, presetName + " = " + xmlParser.getText());
        }
    }
    

    希望这有帮助