我的XML如下
<?xml version="1.0" encoding="utf-8" ?>
<Data>
<Item>
<CategoryId>1</CategoryId>
<Date>20121214</Date>
<Source>mysamplecode@gmail.com</Source>
<ItemDetail>
<quality1>Morning</quality1>
<quality2>12010109Y</quality2>
<quality3>2.00</quality3>
<quality4>7.99</quality4>
</ItemDetail>
<ItemDetail>
<quality1>Afternoon</quality1>
<quality2>12010109B</quality2>
<quality3>900</quality3>
<quality4>83.50</quality4>
</ItemDetail>
<ItemDetail>
<quality1>Dinner</quality1>
<quality2>11271581Y</quality2>
<quality3>16.00</quality3>
<quality4>8.99</quality4>
</ItemDetail>
</Item>
<Item>
<CategoryId>2</CategoryId>
<Date>20121214</Date>
<Source>code@gmail.com</Source>
<ItemDetail>
<quality1>Morning</quality1>
<quality2>12010109Y</quality2>
<quality3>2.00</quality3>
<quality4>7.99</quality4>
</ItemDetail>
</Item>
<Item>
<CategoryId>3</CategoryId>
<Date>20121214</Date>
<Source>code@gmail.com</Source>
<ItemDetail>
<quality1>Afternoon</quality1>
<quality2>12010109B</quality2>
<quality3>900</quality3>
<quality4>83.50</quality4>
</ItemDetail>
</Item>
</Data>
这是我的 ParserClass
public class OrderXMLHandler extends DefaultHandler {
boolean currentElement = false;
String currentValue = "";
CategoryInfo itemdetail;
CategoryInfo categoryInfo;
ArrayList<CategoryInfo> List;
public ArrayList<CategoryInfo> getList() {
return List;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
/* if (qName.equals("Data")){
//List = new ArrayList<CategoryInfo>();
} */
if (localName.equals("maintag"))
{}
else if (qName.equals("Item")) {
List = new ArrayList<CategoryInfo>();
;
}
else if (qName.equals("ItemDetail")) {
categoryInfo = new CategoryInfo();
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (qName.equalsIgnoreCase("CategoryId"))
{
categoryInfo.setCategoryId(currentValue.trim());
listId = currentValue.trim();
}
else if (qName.equalsIgnoreCase("Date"))
{//categoryInfo.setDate(currentValue.trim());
date = currentValue.trim();}
else if (qName.equalsIgnoreCase("Source"))
{//categoryInfo.setSource(currentValue.trim());
source = currentValue.trim();}
else if (qName.equalsIgnoreCase("quality1"))
categoryInfo.setQuality1(currentValue.trim());
else if (qName.equalsIgnoreCase("quality2"))
categoryInfo.setQuality2(currentValue.trim());
else if (qName.equalsIgnoreCase("quality3"))
categoryInfo.setQuality3(currentValue.trim());
else if (qName.equalsIgnoreCase("quality4"))
categoryInfo.setQuality4(currentValue.trim());
else if (qName.equalsIgnoreCase("ItemDetail"))
List.add(categoryInfo);
currentValue = "";
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
}
我认为我没有正确解析我组成的 XML。所以当我启动它时,数据只是容器元素,所以我不知道如何读取它并将每个项目转到我的 Arraylist 的下一个元素,该 Arraylist 进入存储每个项目和信息的 Class CateogoryInfo。每个都有标题和项目详细信息或多个项目详细信息。