如何使用意图选择xml文件并动态解析
我想使用Intent在我的应用程序内选择一个xml文件,然后动态解析它.我知道解析和显示过程,但是我的主要问题是输入流.请注意,xml的选择应动态进行,而不要在资产中进行.有人可以帮助我吗?
I wanted to use intent to pick a xml file inside of my app and then parse it dynamically. I know the parsing and showing process but my main problem is with the inputstream . Please notice that picking xml should be done dynamically not in assets . can anyone help me plz?
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PICKFIlE_RESULT_CODE) {
if (resultCode == RESULT_OK) {
File file = null;
String filepath = data.getData().getPath();
file = new File(filepath);
String v = file.getAbsolutePath();
try
{
InputStream is = new FileInputStream(v);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element = doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("user");
for(int i=0;i<nList.getLength();i++)
{
Node node = nList.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE)
{
Element element2 = (Element)node;
textView.setText(textView.getText()+"\nName : "+getValue("name",element2)+"\n");
textView.setText(textView.getText()+"\nSurname : "+getValue("surname",element2)+"\n");
textView.setText(textView.getText()+"\nSalary : "+getValue("salary",element2)+"\n");
}
}
}
catch (Exception e)
{
}
public void onClick(View v) {
final static private int PICKFILE_RESULT_CODE =10;
try {
Intent intent = new Intent();
intent.setType("file/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICKFIlE_RESULT_CODE);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"No file found",Toast.LENGTH_LONG).show();
}
}
首先,file/*
不是有效的MIME类型.使用有效的MIME类型,如果您要接受任何内容,请使用*/*
.
First, file/*
is not a valid MIME type. Use a valid MIME type, or */*
if you want to accept anything.
第二,ACTION_GET_CONTENT
返回Uri
.该Uri
不是文件.摆脱所有File
逻辑.使用ContentResolver
(来自getContentResolver()
)和openInputStream()
来获取InputStream
,该内容由Uri
标识.
Second, ACTION_GET_CONTENT
returns a Uri
. That Uri
is not a file. Get rid of all your File
logic. Use a ContentResolver
(from getContentResolver()
) and openInputStream()
to get an InputStream
on the content identified by the Uri
.