XmlPullParser解析xml数据
发布时间:2020-12-16 09:05:18 所属栏目:百科 来源:网络整理
导读:解析assets目录下的persons.xml文件; ?xml version="1.0" encoding="UTF-8"? persons person id="1001" name 路人甲/name age25/age /person person id="1002" name路人乙/name age26/age /person /persons public class MainActivity extends Activity {pr
解析assets目录下的persons.xml文件; <?xml version="1.0" encoding="UTF-8"?> <persons> <person id="1001"> <name> 路人甲</name> <age>25</age> </person> <person id="1002"> <name>路人乙</name> <age>26</age> </person> </persons>
public class MainActivity extends Activity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView); textView.setText(""); try { AssetManager assetManager = null; assetManager = this.getAssets(); ParseTools3 parseTools = new ParseTools3(); parseTools.setTextView(textView); parseTools.getRooms(assetManager.open("persons.xml")); } catch (Exception e) { Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show(); textView.append(e.toString()); e.printStackTrace(); } } }
package com.example.xmltestdemo; import java.io.InputStream; import org.xmlpull.v1.XmlPullParser; import android.util.Xml; import android.widget.TextView; public class ParseTools3 { private TextView textView; public void setTextView(TextView textView) { this.textView = textView; } public void getRooms(InputStream xml) throws Exception { XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(xml,"UTF-8"); int event = pullParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { switch (event) { case XmlPullParser.START_DOCUMENT: print("开始解析......n"); break; case XmlPullParser.START_TAG: String name = pullParser.getName(); String value; if (name.equals("persons")) { value = "personsn"; } else if (name.equals("person")) { value = "personn"; value = pullParser.getAttributeValue(0); name = pullParser.getAttributeName(0); } else { value = pullParser.nextText(); } if (name != null) { if (value != null) { print(name + "=" + value); } } if (name == null || value == null) { print("[0]"); } break; case XmlPullParser.END_TAG: if (pullParser.getName() != null && pullParser.getName().equals("person")) { print("end " + pullParser.getName() + "n"); } else if (pullParser.getName() != null && pullParser.getName().equals("persons")) { print("end " + pullParser.getName() + "n"); } break; default: // 空白或者换行 print("; "); break; } event = pullParser.next(); } } private void print(String text) { textView.append(text); } } 运行结果:
本文参考: http://blog.csdn.net/liuhe688/article/details/6415593 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |