n.json文件:
[{name:java,lan:c++,age:17},{name:android,lan:java,age:8}]
pull.xml文件
<?xml version="1.0" encoding="utf-8"?>
<stu>
<name>java</name>
<age>20</age>
<sex>男</sex>
</stu>
<stu>
<name>android</name>
<age>23</age>
<sex>女</sex>
</stu>
解析pull.xml和json
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void parse(View view) { // 创建xml解析器 try { // 设置解析器 // XmlPullParser parser = XmlPullParserFactory.newInstance() // .newPullParser(); XmlPullParser parser = Xml.newPullParser(); // 设置解析的数据源 InputStream ips = this.getAssets().open("pull.xml"); // 设置解析格式 parser.setInput(ips, "UTF-8"); // 设置解析时,可能触发的事件类型 int type = parser.getEventType(); while (type != XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: // 获取元素的名字 String name = parser.getName(); if (name.equals("name")) { String str = parser.nextText(); System.out.println(str); } else if (name.equals("age")) { String age = parser.nextText(); System.out.println(age); } else if (name.equals("sex")) { String sex = parser.nextText(); System.out.println(sex); } break; case XmlPullParser.END_TAG: break; } type = parser.next(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // json解析数据 public void JosnParse(View view) { switch (view.getId()) { case R.id.josnBtn: try { // 使用Json解析数据 InputStream is = this.getAssets().open("n.json"); byte[] by = new byte[is.available()]; is.read(by); String josnStr = new String(by); // 定义解析器 JSONTokener tokener = new JSONTokener(josnStr); // 获取json的数据 JSONArray array = (JSONArray) tokener.nextValue(); for (int i = 0; i < array.length(); i++) { // 将获取的到数组转化成对象 JSONObject obj = (JSONObject) array.get(i); // 解析出对象属性的值 String name = obj.getString("name"); String lan = obj.getString("lan"); String age = obj.getString("age"); System.out.println(name + "<><>" + lan + "<><>" + age); } } catch (Exception e) { e.printStackTrace(); } break; } } }