解析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 = "persons\n"; } else if (name.equals("person")) { value = "person\n"; 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); } }
运行结果:
本文参考:
原文链接:https://www.f2er.com/xml/296591.html