这一篇blog,重要来看看xml文件的Pull解析。
首先,我们自定义个AttributeSet属性:
<resources>
<declare-styleable name="my_xml_test">
<attr name="name" format="string"></attr>
<attr name="age" format="integer"></attr>
<attr name="sex" format="boolean"></attr>
<attr name="school" format="string"></attr>
</declare-styleable>
</resources>
之后,定义一个xml文件:xml_parser_file.xml:
<?xml version="1.0" encoding="utf-8"?>
<infos xmlns:xmltest="http://schemas.android.com/apk/res-auto">
<studentinfo
xmltest:name="xiaoming"
xmltest:age="12"
xmltest:sex="true">
<schoolinfo
xmltest:school="No.one">
</schoolinfo>
<schoolinfo
xmltest:school="No.two">
</schoolinfo>
</studentinfo>
<studentinfo
xmltest:name="xiaohong"
xmltest:age="15"
xmltest:sex="false">
<schoolinfo
xmltest:school="No.three">
</schoolinfo>
<schoolinfo
xmltest:school="No.four">
</schoolinfo>
</studentinfo>
</infos>
注意:三级节点的格式。
一开始疏忽写成了:
<schoolinfo>
xmltest:school="No.four"
</schoolinfo>
结果,老半天没有解析出来。
最后是java中解析:
XmlResourceParser parser = mContext.getResources().getXml(R.xml.xml_parser_file);
AttributeSet attrs = Xml.asAttributeSet(parser);
int type = -1;
TypedArray parentArray = null;
TypedArray childArray = null;
while((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if(parser.getName().equals("studentinfo")) {
parentArray = mContext.obtainStyledAttributes(attrs, R.styleable.my_xml_test);
String name = parentArray.getString(R.styleable.my_xml_test_name);
Log.e("vnbo","vnbo name is "+name);
} else if(parser.getName().equals("schoolinfo")) {
childArray = mContext.obtainStyledAttributes(attrs, R.styleable.my_xml_test);
String school = childArray.getString(R.styleable.my_xml_test_school);
Log.e("vnbo","vnbo school is "+school);
childArray.recycle();
}
break;
case XmlPullParser.END_TAG:
if(parser.getName().equals("studentinfo")) {
parentArray.recycle();
}
break;
}
注意:parentArray的recyle方法的调用位置。注意其调用顺序和childArray的recycle的调用相对顺序。