Android Kotlin解析XML文件(SAX和PULL)

MainActivity.kt

package com.example.fredric.sendrequestwithokhttp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xml.sax.InputSource
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import javax.xml.parsers.SAXParserFactory

class MainActivity : AppCompatActivity(), View.OnClickListener{


    var responseText: TextView? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var sendRequest = findViewById

ContentHander.kt

package com.example.fredric.sendrequestwithokhttp

import android.util.Log
import org.xml.sax.Attributes
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler

class ContentHandler : DefaultHandler() {

    var nodeName: String? = null
    var id: StringBuilder? = null
    var name: StringBuilder? = null
    var version: StringBuilder? = null


    @Throws(SAXException::class)
    override fun startDocument() {
        id = StringBuilder()
        name = StringBuilder()
        version = StringBuilder()
    }


    @Throws(SAXException::class)
    override fun endDocument() {
        super.endDocument()
    }


    @Throws(SAXException::class)
    override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
        nodeName = localName
    }


    @Throws(SAXException::class)
    override fun characters(ch: CharArray, start: Int, length: Int) {
        if("id".equals(nodeName)) {
            id?.append(ch,start,length)
        }else if("name".equals(nodeName)) {
            name?.append(ch,start,length)
        }else if("version".equals(nodeName)) {
            version?.append(ch, start, length)
        }
    }

    @Throws(SAXException::class)
    override fun endElement(uri: String, localName: String, qName: String) {
        if("app".equals(localName)) {
            Log.d("ContentHandler","id is :" + id?.toString()?.trim())
            Log.d("ContentHandler","name is :" + name?.toString()?.trim())
            Log.d("ContentHandler","version is :" + version?.toString()?.trim())

            id?.setLength(0)
            name?.setLength(0)
            version?.setLength(0)
        }
    }

}

activity_main.xml





    

AndroidManifest.xml




    

    
        
            
                

                
            
        
    


运行效果,


Android Kotlin解析XML文件(SAX和PULL)_第1张图片
Screen Shot 2018-07-23 at 7.07.46 AM.png

你可能感兴趣的:(Android Kotlin解析XML文件(SAX和PULL))