XmlPullParser没有看到DOCDECL元素

时间:2012-09-20 09:23:40

标签: android xml-parsing xmlpullparser

我正在使用XML pull解析器来读取XML文件,我想读取DocDecl元素(文件的开头。

这是我正在使用的代码,

FileInputStream inputStream;
XmlPullParserFactory factory;
XmlPullParser xpp;
XmlNode document;

inputStream = new FileInputStream(file);

factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, true);
xpp = factory.newPullParser();
xpp.setInput(inputStream, null);

int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {

    switch (eventType) {
    case XmlPullParser.START_DOCUMENT:
        Log.i("Test XML", "START_DOCUMENT");
        break;
    case XmlPullParser.END_DOCUMENT:
        Log.i("Test XML", "END_DOCUMENT");
        break;
    case XmlPullParser.START_TAG:
        Log.i("Test XML", "START_TAG");
        break;
    case XmlPullParser.END_TAG:
        Log.i("Test XML", "END_TAG");
        break;
    case XmlPullParser.TEXT:
        Log.i("Test XML", "TEXT");
        break;
    case XmlPullParser.CDSECT:
        Log.i("Test XML", "CDSECT");
        break;
    case XmlPullParser.ENTITY_REF:
        Log.i("Test XML", "ENTITY_REF");
        break;
    case XmlPullParser.IGNORABLE_WHITESPACE:
        Log.i("Test XML", "IGNORABLE_WHITESPACE");
        break;
    case XmlPullParser.PROCESSING_INSTRUCTION:
        Log.i("Test XML", "PROCESSING_INSTRUCTION");
        break;
    case XmlPullParser.COMMENT:
        Log.i("Test XML", "COMMENT");
        break;
    case XmlPullParser.DOCDECL:
        Log.i("Test XML", "DOCDECL");
        break;
    default:
        break;
    }
    eventType = xpp.nextToken();
}

这是我得到的结果logcat:

START_DOCUMENT START_TAG START_TAG 文本 END_TAG START_TAG 文本 END_TAG 评论 END_DOCUMENT

使用以下xml

<?xml version="1.0" encoding="utf-8"?>
<root>
    <item>Some text</item>
    <item>Some other text</item>
    <!-- Here's a comment -->
</root>

我正在使用FEATURE_PROCESS_DOCDECL以及nextToken()来确保读取所有内容,但不会处理DocDecl。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

我在xml文件的开头错误地将DOCDECL标记误认为标记,但它用于DOCTYPE声明。

为了实现我想要的,从xml获取版本,编码等,可以使用以下代码:

public static final String PROPERTY_XML_VERSION = "http://xmlpull.org/v1/doc/properties.html#xmldecl-version";
public static final String PROPERTY_XML_STANDALONE = "http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone";

// [...] 

int eventType = xpp.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {
}

String version = (String) xpp.getProperty(PROPERTY_XML_VERSION);
Boolean standalone = (Boolean) xpp.getProperty(PROPERTY_XML_STANDALONE);
String encoding = xpp.getInputEncoding();

我应该更好地阅读XmlPullParser Doc