java – XMLResourceParser,我不知道如何读取我已经关闭的XML

这是我的XML文件一个例子:

<?xml version="1.0" encoding="utf-8"?>
<assurances>
<assurance hasReference="true">
    <message>You're Awesome!</message>
    <reference>Genesis 1:26</reference>
</assurance>
<assurance hasReference="true">
    <message>Your Wonderfull!</message>
    <reference>Genesis 1:26</reference>
</assurance>
</assurances>

我正在使用这样的代码来尝试检索它:

int eventType = -1;
    while(eventType != XmlResourceParser.END_DOCUMENT)
    {
        XmlResourceParser assurances = getResources().getXml(R.xml.assurances); 
        String name = assurances.getText();
        Log.d(TAG, name);

        try {
            if (assurances.getEventType() == XmlResourceParser.START_TAG) {
                String s = assurances.getName();

                if (s.equals("assurance")) {
                    String strMessage = assurances.getAttributeValue(null, "message");
                    String strReference = assurances.getAttributeValue(null, "reference");

                    Log.d(TAG, strMessage);
                    Log.d(TAG, strReference);
                }
            }
        } catch (XmlPullParserException e) {
            // Todo Auto-generated catch block
            e.printstacktrace();
        }
    }

它没有得到数据,我不知道从哪里开始.

解决方法:

您不需要使用getAttributeValue方法,而是需要使用getText()方法.我已对您的代码进行了一些更改,因此如果您使用下面的代码,那么它将正常工作:

int eventType = -1;
while(eventType != XmlResourceParser.END_DOCUMENT)
{
    XmlResourceParser assurances = getResources().getXml(R.xml.assurances); 
    String name = assurances.getText();
    Log.d(TAG, name);

    try {
        if (assurances.getEventType() == XmlResourceParser.START_TAG) {
            String s = assurances.getName();

            if (s.equals("assurance")) {
                assurances.next();   /// moving to the next node
                if(assurances.getName() != null && assurances.getName().equalsIgnoreCase("message")){
                    String strMessage = assurances.getText();  ///to get value getText() method should be used
                    assurances.next();   ///jumping on to the next node
                String strReference = assurances.getText();  ////similar to above
            }

                Log.d(TAG, strMessage);
                Log.d(TAG, strReference);
            }
        }
    } catch (XmlPullParserException e) {
        // Todo Auto-generated catch block
        e.printstacktrace();
    }
}

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念