org.xml.sax.SAXParseException:文档意外结束

时间:2019-07-15 09:06:24

标签: android kotlin xml-parsing

我正在解析已经创建的xml文件并将其存储到内部存储中。

以下是用于创建xml文件的代码:

        val xmlSerializer = Xml.newSerializer()
        val writer = StringWriter()
        val out = mContext.contentResolver.openOutputStream(backupFile)

            xmlSerializer.setOutput(writer)
            xmlSerializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true)
            xmlSerializer.startDocument("UTF-8", true)
            xmlSerializer.startTag("", PARENT1)
            xmlSerializer.attribute("", TOTAL_COUNT, List.size.toString())

            for (i in 0 until List.size) {
                var item = List.get(i)

                xmlSerializer.startTag("", CHILD)

                xmlSerializer.attribute("", CHILD1, item.add)

                xmlSerializer.attribute("", CHILD2, Utils.removeNonPrintable(item.body))

                xmlSerializer.attribute("", CHILD3, Utils.removeNonPrintable(item.name))

                xmlSerializer.endTag("", CHILD)
            }

            xmlSerializer.endTag("", PARENT1)
            xmlSerializer.endDocument()
            xmlSerializer.flush()


            val strData = writer.toString()
            out!!.write(strData.toByteArray())
            out.close()

以下代码用于解析xml文件:

    var List = ArrayList<MsgModel>()
    val file = File(path)
        val inputStream = FileInputStream(file)
        val reader = InputStreamReader(inputStream, UTF8)
        val inSource = InputSource(reader)
        inSource.encoding = UTF8
        val dbf = DocumentBuilderFactory.newInstance()
        val db = dbf.newDocumentBuilder()
        db.setErrorHandler(SimpleErrorHandler())
        val doc = db.parse(inSource)

        val nl = doc.getElementsByTagName(CHILD)
            for (i in 0 until nl.length) {
                var item = DataModel()
                val e = nl.item(i) as Element

                item.child1 = getValue(e, CHILD1)
                item.child2 = getValue(e, CHILD2)
                item.child3 = getValue(e, CHILD3)

                List.add(item)
            }

此行val doc = db.parse(inSource)中出现错误

0 个答案:

没有答案