从Assets读取xml时出现SAX异常

时间:2014-03-21 09:31:14

标签: android xml xml-parsing sax bufferedreader

您好我正在尝试读取我的项目的资源文件夹中的xml文件,但是当它要通过缓冲区读取器读取时会抛出一个SAX异常,我到处搜索以解决这个问题但是没有这样做,它读了xml的某些部分然后通过“文档的结尾”例外,请帮助我这方面,

以下是我的源代码:

MAIN Activty

public class MainActivity extends ListActivity {


    static final String KEY_TITLE = "d:Title"; // parent node
    static final String KEY_CREATIONDATE = "d:Created";
    static final String KEY_DESC = "d:Introduction";
    static final String KEY_CONTENT = "entry";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InputStream in = null;

        AssetManager assetManager = this.getAssets();
        try {

            in = assetManager.open("XMLFile.xml");

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


        BufferedReader reader = new BufferedReader (new InputStreamReader(in),8);

        StringBuilder xml1 = new StringBuilder();
        String cursor;
        try {
            while ( (cursor = reader.readLine()) != null){
                xml1.append(cursor);
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String xml = xml1.toString();
        Log.d("XML", xml);

        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

        XmlParser parser = new XmlParser();
        //String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(in); // getting DOM element

        Log.d("seen1","seen1");
        NodeList nl = doc.getElementsByTagName(KEY_CONTENT);
        Log.d("seen1","seen2");
        // looping through all item nodes <content>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_CREATIONDATE, parser.getValue(e, KEY_CREATIONDATE));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

            // adding HashList to ArrayList
            menuItems.add(map);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_feed,
                new String[] { KEY_TITLE, KEY_CREATIONDATE, KEY_DESC }, new int[] {
                        R.id.Title, R.id.creationDate , R.id.desciption });

        setListAdapter(adapter);

    }
}

这是我的xml解析器

public class XmlParser {

    // constructor
    public XmlParser() {
    }

BufferedReader reader;
    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(InputStream in){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();


        try {
            reader = new BufferedReader( new InputStreamReader (in, "UTF-8" ),8);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(reader);
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error1: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error2: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error3: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}

LOG CAT:

03-21 14:17:59.375: E/Error2:(27301): Unexpected end of document
03-21 14:17:59.375: D/seen1(27301): seen1
03-21 14:17:59.375: D/AndroidRuntime(27301): Shutting down VM
03-21 14:17:59.375: W/dalvikvm(27301): threadid=1: thread exiting with uncaught exception (group=0x4001d578)
03-21 14:17:59.445: E/AndroidRuntime(27301): FATAL EXCEPTION: main
03-21 14:17:59.445: E/AndroidRuntime(27301): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webpreneur/com.example.webpreneur.MainActivity}: java.lang.NullPointerException
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.app.ActivityThread.access$1500(ActivityThread.java:121)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.os.Looper.loop(Looper.java:138)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.app.ActivityThread.main(ActivityThread.java:3701)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at java.lang.reflect.Method.invokeNative(Native Method)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at java.lang.reflect.Method.invoke(Method.java:507)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at dalvik.system.NativeStart.main(Native Method)
03-21 14:17:59.445: E/AndroidRuntime(27301): Caused by: java.lang.NullPointerException
03-21 14:17:59.445: E/AndroidRuntime(27301):    at com.example.webpreneur.MainActivity.onCreate(MainActivity.java:74)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-21 14:17:59.445: E/AndroidRuntime(27301):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
03-21 14:17:59.445: E/AndroidRuntime(27301):    ... 11 more

在logcat中显示的XML文件,在此之后不通过SAX异常“doucment结束”

 03-21 14:17:59.295: D/XML(27301): <?xml version="1.0" encoding="utf-8"?><feed xml:base="https://portal.wow2.telenor.com/global/newscentre/_api/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">  <id>032acc78-4645-416d-8f57-69f9de340d9e</id>  <title />  <updated>2014-03-20T06:20:12Z</updated>  <entry m:etag="&quot;97&quot;">    <id>bd4e2024-d7dd-4c09-bfdc-0364d88c9b35</id>    <category term="SP.Data.PagesItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />    <link rel="edit" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FirstUniqueAncestorSecurableObject" type="application/atom+xml;type=entry" title="FirstUniqueAncestorSecurableObject" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/FirstUniqueAncestorSecurableObject" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/RoleAssignments" type="application/atom+xml;type=feed" title="RoleAssignments" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/RoleAssignments" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/AttachmentFiles" type="application/atom+xml;type=feed" title="AttachmentFiles" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/AttachmentFiles" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ContentType" type="application/atom+xml;type=entry" title="ContentType" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/ContentType" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FieldValuesAsHtml" type="application/atom+xml;type=entry" title="FieldValuesAsHtml" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/FieldValuesAsHtml" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FieldValuesAsText" type="application/atom+xml;type=entry" title="FieldValuesAsText" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/FieldValuesAsText" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FieldValuesForEdit" type="application/atom+xml;type=entry" title="FieldValuesForEdit" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/FieldValuesForEdit" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/File" type="application/atom+xml;type=entry" title="File" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/File" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Folder" type="application/atom+xml;type=entry" title="Folder" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/Folder" />    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ParentList" type="application/atom+xml;type=entry" title="ParentList" href="Web/Lists(guid'b1b97552-232e-46e3-b9ec-f864a85f7177')/Items(1)/ParentList" />    <title />    <updated>2014-03-20T06:20:12Z</updated>    <author>      <name />    </author>    <content type="application/xml">      <m:properties>        <d:FileSystemObjectType m:type="Edm.Int32">0</d:FileSystemObjectType>        <d:Id m:type="Edm.Int32">1</d:Id>        <d:ContentTypeId>0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00C5D7502BB1BE4006888BDEE5E78E104B00A287E6D310B04CEF9229EAFF95D33A5600CBA1EC286E8DFD469D11D1225435F896</d:ContentTypeId>        <d:OData__ModerationComments m:null="true" />        <d:Title>News Center</d:Title>        <d:OData__dlc_DocId>67XPVZAHCTHM-7-1</d:OData__dlc_DocId>        <d:OData__dlc_DocIdUrl m:type="SP.FieldUrlValue">          <d:Description>67XPVZAHCTHM-7-1</d:Description>          <d:Url>https://portal.wow2.telenor.com/global/newscentre/_layouts/15/DocId
        03-21 14:17:59.345: D/dalvikvm(27301): GC_CONCURRENT freed <1K, 44% free 8831K/15559K, external 2058K/2129K, paused 2ms+2ms
        03-21 14:17:59.375: E/Error2:(27301): Unexpected end of document
        03-21 14:17:59.375: D/seen1(27301): seen1

1 个答案:

答案 0 :(得分:1)

请按照以下步骤操作:

  1. 从以下链接jsonlib

  2. 下载jar文件
  3. 将jar文件粘贴到libs

  4. 添加以下演示代码:


  5. @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        String xmldata = null;
        try {
            xmldata = convertStreamToString(getAssets().open("XMLFILENAME"));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        JSONObject jsonObj = null;
        try {
            jsonObj = XML.toJSONObject(xmldata);
        } catch (JSONException e) {
            Log.e("JSON exception", e.getMessage());
            e.printStackTrace();
        }
    
        Log.d("XML", xmldata);
        Log.d("JSON", jsonObj.toString());
    }
    
    public static String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
          sb.append(line).append("\n");
        }
        reader.close();
        return sb.toString();
    }