1

我正在尝试学习如何在 Android 中使用 SAX 解析器解析 xml 文件。

我放置了一个示例 xml 文件: res/xml/example.xml 这是 xml 代码

<?xml version="1.0" encoding="utf-8"?>
<maintag>
    <item>
        <name>
            AndroidPeople
        </name>

        <website category="android" >
            www.androidpeople.com
        </website>
    </item>

    <item>
        <name>
            iPhoneAppDeveloper
        </name>

        <website category="iPhone" >
            www.iphone-app-developer.com
        </website>
    </item>
</maintag>

这是主要的 Activity 类

package com.me.xml_trail;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class XMLParsingExample extends Activity
{
    /** Create Object For SiteList Class */
    SitesList sitesList = null;

    SAXParserFactory spf;
    SAXParser sp;
    XMLReader xr;
    InputSource is;
    MyXMLHandler myXMLHandler;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        /** Create a new layout to display the view */
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(1);

        /** Create a new textview array to display the results */
        TextView name[];
        TextView website[];
        TextView category[];

        try
        {
            /** Handling XML */
            spf = SAXParserFactory.newInstance();
        }
        catch (Exception e)
        {
            Log.d("mytag","1 " + e);
        }

        try
        {
            sp = spf.newSAXParser();
        }
        catch (Exception e)
        {
            Log.d("mytag","2 " + e);
        }

        try
        {
            xr = sp.getXMLReader();
        }
        catch (Exception e)
        {
            Log.d("mytag","3 " + e);
        }

        try
        {           
            /** Send URL to parse XML Tags */
            is = new InputSource(getResources().openRawResource(R.xml.example));
            is.setEncoding("utf-8");
        }
        catch (Exception e)
        {
            Log.d("mytag","4 " + e);
        }

        try
        {
            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            myXMLHandler = new MyXMLHandler();
        }
        catch (Exception e)
        {
            Log.d("mytag","5 " + e);
        }

        try
        {
            xr.setContentHandler(myXMLHandler);
        }
        catch (Exception e)
        {
            Log.d("mytag","6 " + e);
        }

        try
        {
            xr.parse(new InputSource(is.getByteStream()));      
        }
        catch (Exception e)
        {
            Log.d("mytag","7 " + e);
        }

        /** Get result from MyXMLHandler SitlesList Object */
        sitesList = MyXMLHandler.sitesList;

        /** Assign textview array lenght by arraylist size */
        name = new TextView[sitesList.getName().size()];
        website = new TextView[sitesList.getName().size()];
        category = new TextView[sitesList.getName().size()];

        /** Set the result text in textview and add it to layout */
        for (int i = 0; i < sitesList.getName().size(); i++)
        {
            name[i] = new TextView(this);
            name[i].setText("Name = " + sitesList.getName().get(i));
            website[i] = new TextView(this);
            website[i].setText("Website = " + sitesList.getWebsite().get(i));
            category[i] = new TextView(this);
            category[i].setText("Website Category = " + sitesList.getCategory().get(i));

            layout.addView(name[i]);
            layout.addView(website[i]);
            layout.addView(category[i]);
        }

        /** Set the layout view to display */
        setContentView(layout);
    }
}

这是我的日志猫

cscCountry is not German : BTU

 7 org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: not well-formed (invalid token)

 threadid=1: thread exiting with uncaught exception (group=0x40018578)

 FATAL EXCEPTION: main

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.me.xml_trail/com.me.xml_trail.XMLParsingExample}: java.lang.NullPointerException

 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)

 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)

 at android.app.ActivityThread.access$1500(ActivityThread.java:117)

 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)

 at android.os.Handler.dispatchMessage(Handler.java:99)

 at android.os.Looper.loop(Looper.java:130)

 at android.app.ActivityThread.main(ActivityThread.java:3687)

 at java.lang.reflect.Method.invokeNative(Native Method)

 at java.lang.reflect.Method.invoke(Method.java:507)

 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)

 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)

 at dalvik.system.NativeStart.main(Native Method)

 Caused by: java.lang.NullPointerException

 at com.me.xml_trail.XMLParsingExample.onCreate(XMLParsingExample.java:113)

 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

 ... 11 more

问题出在 xr.parse(new InputSource(is.getByteStream())); 为什么我会得到这个

4

2 回答 2

1

我通过更改解析 xml 的方式来修复它

InputStream response=context.getAssets().open("your.xml");

Xml.parse(response, Xml.Encoding.UTF_8,rootElement.getContentHandler());

带有本地 XML 文件的 SAXParser

于 2012-07-26T19:05:48.793 回答
-1

回到原来的问题,我也发现了这个错误。我将它追踪到 XML 输入,由于某种原因它为空。我最初尝试将 XML 解析为 r.xml.example.xml 下的本地资源,但失败了,即使来自http://www.androidpeople.com/xml-parsing的代码示例

由于远程 XML 和本地 XML 生成了两个不同的结果,我知道这是问题的根源。在尝试多次解析 XML 文件后,我将其移至 R.raw.example.xml 并且它起作用了。

我不知道为什么,也不怀疑这是一个明确的答案。我唯一能想到的不同之处就是手动写出 XML。这可能是我从网站上复制的原始 XML 的编码错误。

环境:Intellij 12 Android SDK 4.03 Java 1.6 SDK

请注意,解析构成程序一部分的 XML 不需要请求新的权限。

于 2013-07-02T01:32:24.403 回答