在Android中读取外部XML文件

时间:2019-01-16 10:03:15

标签: android xml xml-parsing android-xml

如何在android应用中读取外部XML文件的此类数据并在视图中设置

<?XML version="1.0"?>  
<OKV
r="129120190116115414009" 
a="Address" g="male" m="123456" 
e="email" d="14021996" i="imagelink" 
n="My Name" v="1"/>

2 个答案:

答案 0 :(得分:1)

对于上面的xml示例,您可以尝试下面的解析器

public class MainActivity extends Activity {

    ArrayList<String> r_no;
    int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         r_no = new ArrayList<String>();

         try {
         File file = new File("mnt/sdcard/yourxmlfile.xml");
         InputStream is = new FileInputStream(file.getPath());
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document doc = db.parse(new InputSource(is));
         doc.getDocumentElement().normalize();

         NodeList n = doc.getElementsByTagName("OKV");

         for (int j = 0; j < n.getLength(); j++) {
             Node node = n.item(j);

             Element fstElmnt = (Element) node;

             r_no.add(fstElmnt.getAttribute("r"));

        }
     } catch (Exception e) {
         System.out.println("XML Pasing Excpetion = " + e);
     }
 }
}

有关更多信息,请检查official Document

答案 1 :(得分:1)

在Android中解析XML的三种方法

  • DOM Parsers
  • SAX Parsers
  • XMLPullParser

遵循这些步骤

首先,在清单文件中添加 READ_EXTERNAL_STORAGE 权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

然后检查runtime permission是否适用于Android棉花糖及更高版本

  

因为,从Android 6.0(API级别23)开始,用户在应用程序运行时(而不是在安装应用程序时)授予应用程序权限

 int grant = ContextCompat.checkSelfPermission(this, permission);
 if (grant != PackageManager.PERMISSION_GRANTED) {
     String[] permission_list = new String[1];
     permission_list[0] = permission;
     ActivityCompat.requestPermissions(this, permission_list, 1);
 }

然后解析您的xml

以下是使用 DOM Parsers

的示例代码

示例代码

  

创建模型类

public class Model {

    String rValue, aValue, eValue, nValue, gValue, dValue, vValue, mValue, iValue;

    public String getrValue() {
        return rValue;
    }

    public void setrValue(String rValue) {
        this.rValue = rValue;
    }

    public String getaValue() {
        return aValue;
    }

    public void setaValue(String aValue) {
        this.aValue = aValue;
    }

    public String geteValue() {
        return eValue;
    }

    public void seteValue(String eValue) {
        this.eValue = eValue;
    }

    public String getnValue() {
        return nValue;
    }

    public void setnValue(String nValue) {
        this.nValue = nValue;
    }

    public String getgValue() {
        return gValue;
    }

    public void setgValue(String gValue) {
        this.gValue = gValue;
    }

    public String getdValue() {
        return dValue;
    }

    public void setdValue(String dValue) {
        this.dValue = dValue;
    }

    public String getvValue() {
        return vValue;
    }

    public void setvValue(String vValue) {
        this.vValue = vValue;
    }

    public String getmValue() {
        return mValue;
    }

    public void setmValue(String mValue) {
        this.mValue = mValue;
    }

    public String getiValue() {
        return iValue;
    }

    public void setiValue(String iValue) {
        this.iValue = iValue;
    }
}
  

MainActivity代码

public class MainActivity extends AppCompatActivity {

    List<Model> modelArrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // first check for runtime permission
        String permission = Manifest.permission.READ_EXTERNAL_STORAGE;
        int grant = ContextCompat.checkSelfPermission(this, permission);
        if (grant != PackageManager.PERMISSION_GRANTED) {
            String[] permission_list = new String[1];
            permission_list[0] = permission;
            ActivityCompat.requestPermissions(this, permission_list, 1);
        }else {
            ParseXML();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "READ_EXTERNAL_STORAGE permission granted", Toast.LENGTH_SHORT).show();
                ParseXML();
            } else {
                Toast.makeText(MainActivity.this, " READ_EXTERNAL_STORAGE permission not granted", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void ParseXML() {

        File dir = Environment.getExternalStorageDirectory();
        File yourFile = new File(dir, "test.xml");

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        try {

            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(yourFile);
            doc.getDocumentElement().normalize();

            Log.e("Root_element" , doc.getDocumentElement().getNodeName());
            NodeList nodeList = doc.getElementsByTagName("OKV");

            modelArrayList = new ArrayList<Model>();


            for (int i = 0; i < nodeList.getLength(); i++) {

                Element element = (Element) nodeList.item(i);

                Model model = new Model();
                model.setrValue(element.getAttribute("r"));
                model.setaValue(element.getAttribute("a"));
                model.setgValue(element.getAttribute("g" ));
                model.setmValue(element.getAttribute("m" ));
                model.seteValue(element.getAttribute("e" ));
                model.setdValue(element.getAttribute("d" ));
                model.setiValue(element.getAttribute("i"));
                model.setnValue(element.getAttribute("n" ));
                model.setvValue(element.getAttribute("v"));

                modelArrayList.add(model);



            }

            for (int i = 0; i < modelArrayList.size(); i++) {

                Log.e("DATA_VALUE", modelArrayList.get(i).getaValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getdValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).geteValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getnValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getvValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getgValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getrValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getiValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getmValue());
            }
        } catch (SAXException | ParserConfigurationException | IOException e1) {
            e1.printStackTrace();
        }

    }


}

输出

01-19 13:23:39.545 15689-15689/neel.com.demo E/Root_element: OKV
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: Address
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: 14021996
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: email
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: My Name
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: 1
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: male
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: 129120190116115414009
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: imagelink
01-19 13:23:39.545 15689-15689/neel.com.demo E/DATA_VALUE: 123456
  

有关更多信息,请查看以下文章

更新

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


import com.nbsp.materialfilepicker.MaterialFilePicker;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


public class MainActivity extends AppCompatActivity {

    List<Model> modelArrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // first check for runtime permission
        String permission = Manifest.permission.READ_EXTERNAL_STORAGE;
        int grant = ContextCompat.checkSelfPermission(this, permission);
        if (grant != PackageManager.PERMISSION_GRANTED) {
            String[] permission_list = new String[1];
            permission_list[0] = permission;
            ActivityCompat.requestPermissions(this, permission_list, 1);
        } else {
            pickFile();
        }
    }

    private void pickFile() {
        new MaterialFilePicker()
                .withActivity(this)
                .withRequestCode(1)
                .withFilterDirectories(true)
                .withHiddenFiles(true)
                .start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {

            String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
            Log.e("FILE_PATH", filePath);
            ParseXML(filePath);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "READ_EXTERNAL_STORAGE permission granted", Toast.LENGTH_SHORT).show();

                pickFile();
            } else {
                Toast.makeText(MainActivity.this, " READ_EXTERNAL_STORAGE permission not granted", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void ParseXML(String path) {


        File yourFile = new File(path);

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        try {

            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(yourFile);
            doc.getDocumentElement().normalize();

            Log.e("Root_element", doc.getDocumentElement().getNodeName());
            NodeList nodeList = doc.getElementsByTagName("OKV");

            modelArrayList = new ArrayList<Model>();


            for (int i = 0; i < nodeList.getLength(); i++) {

                Element element = (Element) nodeList.item(i);

                Model model = new Model();
                model.setrValue(element.getAttribute("r"));
                model.setaValue(element.getAttribute("a"));
                model.setgValue(element.getAttribute("g"));
                model.setmValue(element.getAttribute("m"));
                model.seteValue(element.getAttribute("e"));
                model.setdValue(element.getAttribute("d"));
                model.setiValue(element.getAttribute("i"));
                model.setnValue(element.getAttribute("n"));
                model.setvValue(element.getAttribute("v"));

                modelArrayList.add(model);


            }

            for (int i = 0; i < modelArrayList.size(); i++) {

                Log.e("DATA_VALUE", modelArrayList.get(i).getaValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getdValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).geteValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getnValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getvValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getgValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getrValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getiValue());
                Log.e("DATA_VALUE", modelArrayList.get(i).getmValue());
            }
        } catch (SAXException | ParserConfigurationException | IOException e1) {
            e1.printStackTrace();
        }

    }


}

注意用于我使用过AndroidFileExplorer

的文件选择器