XmlResourceParser使用例子
对于像这样一个xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<level>
<begin x="80" y="415" />
<end x="720" y="415" />
<walls count="3">
<wall left="195" top="130" right="201" bottom="477" />
<wall left="400" top="6" right="406" bottom="352" />
<wall left="605" top="130" right="611" bottom="477" />
</walls>
<holes count="5">
<hole x="130" y="106" />
<hole x="270" y="106" />
<hole x="270" y="424" />
<hole x="470" y="328" />
<hole x="730" y="60" />
</holes>
</level>
可以这样来读取
XmlResourceParser xmlParser = this.mActivity.getResources().getXml(R.xml.level001 + idxLevelXml);
int eventType = xmlParser.getEventType();
while (eventType != XmlResourceParser.END_DOCUMENT)
{
if(eventType == XmlResourceParser.START_TAG)
{
String strName = xmlParser.getName();
if (strName.equals("begin"))
{
int m = xmlParser.getAttributeIntValue(0, -1);
int n = xmlParser.getAttributeIntValue(1, -1);
setBBegin(m, n);
}
else if(strName.equals("end"))
{
int i2 = xmlParser.getAttributeIntValue(0, -1);
int i3 = xmlParser.getAttributeIntValue(1, -1);
setEnd(i2, i3);
}
else if(strName.equals("walls"))
{
int nWallCnt = xmlParser.getAttributeIntValue(0, 0);
mwalls = new Rect[nWallCnt];
int nCount = 0;
do
{
if(XmlResourceParser.START_TAG == xmlParser.getEventType()
&& xmlParser.getName().equals("wall"))
{
int iLeft = xmlParser.getAttributeIntValue(0, -1);
int iTop = xmlParser.getAttributeIntValue(1, -1);
int iRight = xmlParser.getAttributeIntValue(2, -1);
int iBottom = xmlParser.getAttributeIntValue(3, -1);
mWalls[nCount] = new Rect(iLeft, iTop, iRight, iBottom);
nCount ++;
}
xmlParser.next();
}while(nCount < nWallCnt);
}
else if (strName.equals("holes"))
{
int nHoleCnt = xmlParser.getAttributeIntValue(0, 0);
mHoles = new Point[nHoleCnt];
int nCount = 0;
do
{
if(XmlResourceParser.START_TAG == xmlParser.getEventType()
&& xmlParser.getName().equals("hole"))
{
int iX = xmlParser.getAttributeIntValue(0, -1);
int iY = xmlParser.getAttributeIntValue(1, -1);
mHoles[nCount] = new Point(iX, iY);
nCount++;
}
xmlParser.next();
}while(nCount < nHoleCnt);
}
}
eventType = xmlParser.next();
}
xmlParser.close();


浙公网安备 33010602011771号