我正在尝试解析res > xml > my_file.xml
上的XML资源文件。它似乎停留在第-1行,我不太明白为什么会这样。
以下是代码:
class SPXMLParser(val context: Context){
fun parse(): MutableList<Node> {
Log.d("PONY", "We are inside SPXMLParser.parse()")
val parser = context.resources.getXml(R.xml.my_file)
Log.d("PONY", "Parser created text: ${parser.text} Parser line: ${parser.lineNumber}")
return readFeed(parser)
}
private fun readFeed(parser: XmlPullParser): MutableList<Node> {
Log.d("PONY", "Inside readFeed")
val entries = mutableListOf<Node>()
Log.d("PONY", "Before while text: ${parser.text} Parser line: ${parser.lineNumber}")
while (parser.eventType != XmlPullParser.END_DOCUMENT) {
Log.d("PONY", "While condition met text: ${parser.text} Parser line: ${parser.lineNumber}")
val name = parser.name
// Starts by looking for the entry tag
if (name == "node") {
entries.add(readEntry(parser))
} else {
skip(parser)
}
parser.next()
}
Log.d("PONY", "Before returning from readFeed")
return entries
}
// ...
private fun skip(parser: XmlPullParser) {
Log.d("PONY", "Inside skip function")
if (parser.eventType != XmlPullParser.START_TAG) {
Log.d("PONY", "About to throw up")
throw IllegalStateException()
}
var depth = 1
while (depth != 0) {
Log.d("PONY", "Inception loop")
when (parser.next()) {
XmlPullParser.END_TAG -> depth--
XmlPullParser.START_TAG -> depth++
}
}
Log.d("PONY", "Exit skip function")
}
}
以下是我们在logcat中可以阅读的内容:
06-01 15:51:01.972 12030-12030/com.example.learningtoparse D/PONY: We are inside onCreate
06-01 15:51:01.981 12030-12030/com.example.learningtoparse D/PONY: Parser has been created
We are inside SPXMLParser.parse()
06-01 15:51:01.982 12030-12030/com.example.learningtoparse D/PONY: Parser created text: null Parser line: -1
Inside readFeed
Before while text: null Parser line: -1
While condition met text: null Parser line: -1
Else condition
Inside skip function
About to throw up
我错过了什么?为什么行-1?
编辑:发布函数skip()
并更新日志跟踪。我知道应用程序因为未处理的异常IllegalStateException
被抛出而停止,但关于解析器为什么排成一行“-1”的问题仍然存在。
EDIT2:I found this question that might be related to mine。 但是,答案似乎有点不确定。我的文件中也有XML Prolog:
<?xml version="1.0" encoding="UTF-8"?>
该答案的建议是读取了XML Prolog但我们仍处于事件START_DOCUMENT
,因为尚未读取根标记。