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?

2
  • did you find some solution? I am facing same issue. Commented Dec 21, 2021 at 19:55
  • @AbdulSalam try using skip function in the readAd. If possible share the sample project over github. Can take a look if you want Commented Dec 23, 2021 at 10:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.