1

I have to parse the below xml

<?xml version="1.0" encoding="UTF-8"?>
<VAST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
<Ad id="5440583487">
    <InLine>
        <AdSystem>DSLKD</AdSystem>
    </InLine>
</Ad>
<Ad id="239492834">
    <InLine>
        <AdSystem>SLKSD</AdSystem>
    </InLine>
</Ad>
<Ad id="23042349">
    <InLine>
        <AdSystem>FKDF</AdSystem>
    </InLine>
</Ad>
</VAST>

I am using XmlPullParser to parse it. I am able to get first ad id but not after that. This is my code

class DataLoader(val context: Context) {

suspend fun getPlayableUrls(){
    withContext(Dispatchers.IO){
        val inputStream = context.assets.open("ads_players2.xml")
        inputStream.use { inputStream ->
            val parser: XmlPullParser = Xml.newPullParser()
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
            parser.setInput(inputStream, null)
            parser.nextTag()
            readFeed(parser)
        }
    }
}

private fun readFeed(parser: XmlPullParser)  {
    parser.require(XmlPullParser.START_TAG, null, "VAST")
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.eventType != XmlPullParser.START_TAG) {
            continue
        }
        if (parser.name == "Ad") {
            println("ad id    ---->".plus(parser.getAttributeValue(null,"id")))
            readAd(parser)
        } else {
            skip(parser)
        }
    }
}

private fun readAd(parser: XmlPullParser){
    parser.require(XmlPullParser.START_TAG, null, "Ad")
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.eventType != XmlPullParser.START_TAG) {
            continue
        }
        println("ad id    ---->".plus(parser.getAttributeValue(null,"id")))
    }
}

private fun skip(parser: XmlPullParser) {
    if (parser.eventType != XmlPullParser.START_TAG) {
        throw IllegalStateException()
    }
    var depth = 1
    while (depth != 0) {
        when (parser.next()) {
            XmlPullParser.END_TAG -> depth--
            XmlPullParser.START_TAG -> depth++
        }
    }
}
}

What is wrong over here?

WISHY
  • 11,067
  • 25
  • 105
  • 197

0 Answers0