学习Android解析xml文件过程中,发现标签里的属性在被读取后顺序发生错乱。
期待顺序为 :
<customer name="Andy" tel="888888" email="123456@qq.com">Andy</customer>
读取顺序为:
<!--布局文件如下:-->
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.xmltest.MainActivity">
<TextView
android:textSize="25dp"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="正在读取XML..."
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
<!--自定义看一个customers的xml文件-->
<?xml version="1.0" encoding="utf-8"?>
<customers>
<customer name="Andy" tel="888888" email="123456@qq.com">Andy</customer>
<customer name="Jack" tel="666666" email="654321@qq.com">Jack</customer>
<customer name="Rose" tel="999999" email="456789@qq.com">Rose</customer>
</customers>
// 活动代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
XmlResourceParser xmlResourceParser=getResources().getXml(R.xml.customers); // 获取到xml文档
StringBuilder sb=new StringBuilder("");
try {
while(xmlResourceParser.getEventType()!=XmlResourceParser.END_DOCUMENT)
{
if(xmlResourceParser.getEventType()==XmlResourceParser.START_TAG) // 开始标记
{
String tag_name=xmlResourceParser.getName(); // 获取到标记名称
if(tag_name.equals("customer"))
{
String name,tel,email;
name=xmlResourceParser.getAttributeValue(0);
tel=xmlResourceParser.getAttributeValue(1);
email=xmlResourceParser.getAttributeValue(2);
sb.append("姓名:"+name+" ");
sb.append("电话:"+tel+" ");
sb.append("邮箱:"+email+" ");
sb.append("\n");
}
}
xmlResourceParser.next(); // 下一个标记
}
TextView textView=findViewById(R.id.text);
textView.setText(sb.toString());
}catch (Exception e)
{
e.printStackTrace();
}
}
}