【问题标题】:How to parse xml from url link in kotlin, android如何从 kotlin,android 中的 url 链接解析 xml
【发布时间】:2019-07-10 22:02:45
【问题描述】:

我试图从 url 链接解析 xml,例如:http://a.cdn.searchspring.net/help/feeds/sample.xml,我可以从文件中解析它,但不能从 url 链接中解析。这是我的代码:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.SimpleAdapter
import android.widget.ListView
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.xml.sax.InputSource
import org.xml.sax.SAXException
import java.io.IOException
import java.net.URL
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var empDataHashMap = HashMap<String, String>()
        var empList: ArrayList<HashMap<String, String>> = ArrayList()
        var url = URL("http://a.cdn.searchspring.net/help/feeds/sample.xml")

            val lv = findViewById<ListView>(R.id.listView)

            // Using a background thread to do network code
            val thread = object : Thread() {
                override fun run() {
                    try {
                        // Comment-out this line of code
                        // val istream = assets.open("empdetail.xml")
                        val builderFactory = DocumentBuilderFactory.newInstance()
                        val docBuilder = builderFactory.newDocumentBuilder()
                        val doc = docBuilder.parse(InputSource(url.openStream()))
                        // reading player tags
                        val nList = doc.getElementsByTagName("Product")
                        for (i in 0 until nList.length) {
                            if (nList.item(0).nodeType.equals(Node.ELEMENT_NODE)) {
                                empDataHashMap = HashMap()
                                val element = nList.item(i) as Element
                                empDataHashMap.put("name", getNodeValue("name", element))
                                empDataHashMap.put("id", getNodeValue("id", element))
                                empDataHashMap.put("brand", getNodeValue("brand", element))

                                empList.add(empDataHashMap)
                            }
                        }

                        val adapter = SimpleAdapter(
                                this@MainActivity,
                                empList,
                                R.layout.custom_list,
                                arrayOf("name", "id", "brand"),
                                intArrayOf(R.id.name, R.id.ratings, R.id.role)
                        )

                        runOnUiThread {
                            lv.setAdapter(adapter)
                        }
                    } catch (e: IOException) {
                        e.printStackTrace()
                    } catch (e: ParserConfigurationException) {
                        e.printStackTrace()
                    } catch (e: SAXException) {
                        e.printStackTrace()
                    }
                }
            }

            thread.start()
        }


    //return node value
    public fun getNodeValue(tag: String, element: Element): String{
        val nodeList = element.getElementsByTagName(tag)
        val node = nodeList.item(0)
        if(node != null){
            if(node.hasChildNodes()){
                val child = node.firstChild
                while(child!=null){
                    if(child.nodeType === org.w3c.dom.Node.TEXT_NODE)
                    {
                        return child.nodeValue
                    }
                }
            }
        }
        return ""
    }
}

我还在清单文件中添加了互联网权限。在我运行代码时,此代码正在运行而没有任何警告。但只是一个空的活动来了。那里没有显示任何数据。

【问题讨论】:

    标签: android xml parsing url kotlin


    【解决方案1】:

    我认为您使用错误的方式从 url 获取 xml。 您应该从 url 请求数据。

    像这样在java中:

    HttpURLConnection connection = null;
        try {
            URL url = new URL(target);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.connect();
        }
    

    并使用它来获取字符串中的数据:

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line).append("\n");
    }
    br.close();
    return sb.toString();
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-08-17
      • 2017-03-22
      • 1970-01-01
      • 2020-04-05
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多