您的代码片段不是 XML……请参阅可扩展标记语言 (XML) 1.1(第二版)。
- c 属性值未关闭。
- x 标签未关闭。
- 你有多个根...</li>
If these are typos, you should correct that and I'll check if I can provide a real answer…</p>
As a responsible programmer, don't use that format but rather migrate the data to a well-defined format but not bother to use this kind of corrupted format on a client application.
Update
Here is a quick-and-dirty implementation (using my own Vehicle POJO):
public class Butelo extends Activity
{
public static String TAG = "SO Butelo";
public static List<Vehicle> vehicles = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<cars><a b=\"car\" c=\"blue\"><x year=\"01\"/><x year=\"03\"/></a><a b=\"truck\" c=\"red\"><x year=\"04\"/><x year=\"85\"/></a></cars>") );
int eventType = xpp.getEventType();
boolean done = false;
Vehicle currentVehicle = null;
while (eventType != XmlPullParser.END_DOCUMENT && !done) {
String name = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
vehicles = new ArrayList<Vehicle>();
break;
case XmlPullParser.START_TAG:
name = xpp.getName();
if (name.equals("a")){
currentVehicle = new Vehicle();
currentVehicle.setType(xpp.getAttributeValue(null, "b"));
currentVehicle.setColor(xpp.getAttributeValue(null, "c"));
} else if (name.equals("x")) {
currentVehicle.appendToYears(xpp.getAttributeValue(null, "year"));
}
break;
case XmlPullParser.END_TAG:
name = xpp.getName();
if (name.equals("a")){
vehicles.add(currentVehicle);
}
break;
}
eventType = xpp.next();
}
} catch (FileNotFoundException e) {
Log.e(TAG, "", e.fillInStackTrace());
} catch (XmlPullParserException e) {
Log.e(TAG, "", e.fillInStackTrace());
} catch (IOException e) {
Log.e(TAG, "", e.fillInStackTrace());
}
for(int i=0;i<vehicles.size();i++) {
Vehicle vehicle = vehicles.get(i);
Log.v(TAG, vehicle.toString());
}
}
private class Vehicle {
private String mType;
private String mColor;
private String mYears = "";
void setType(String type) { mType = type; }
String getType() { return mType; }
void setColor(String color) { mColor = color; }
String getColor() { return mColor; }
void appendToYears(String year) {
StringBuilder sb = new StringBuilder(mYears);
if (!mYears.equals("")) {
sb.append(", ");
}
sb.append(year);
mYears = sb.toString();
}
String getYears() { return mYears; }
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[\"");
sb.append(mType);
sb.append("\", \"");
sb.append(mColor);
sb.append("\", \"");
sb.append(mYears);
sb.append("\"]");
return sb.toString();
}
}
}
That's just to put you on your own way…</p>