こんにちは、これを試してみてください。正常に動作しています。
RAWフォルダに入れたXMLファイルと名前「abc.xml」
<?xml version="1.0" encoding="utf-8"?>
<Tables><Table id="Table142" rowOrder="141">
<TeamIDGiven>7</TeamIDGiven>
<City>Wolfpack</City>
<TeamName>North Carolina State</TeamName>
</Table>
<Table id="Table143" rowOrder="142">
<TeamIDGiven>308</TeamIDGiven>
<City/>
<TeamName>North Dakota</TeamName>
</Table>
<Table id="Table144" rowOrder="143">
<TeamIDGiven>309</TeamIDGiven>
<City>Bison</City>
<TeamName>North Dakota State</TeamName>
</Table></Tables>
以下のようにパブリッククラスBeanを作成します
public class Table_Beans {
private String TeamIDGiven;
private String City;
private String TeamName;
public String getTeamIDGiven() {
return TeamIDGiven;
}
public void setTeamIDGiven(String teamIDGiven) {
TeamIDGiven = teamIDGiven;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getTeamName() {
return TeamName;
}
public void setTeamName(String teamName) {
TeamName = teamName;
}
}
以下のXMLhandlerクラス。
public class TestXMLhandler extends DefaultHandler {
private StringBuffer buffer = new StringBuffer();
private ArrayList<Table_Beans> data_list;
private Table_Beans data;
public ArrayList<Table_Beans> getData() {
return data_list;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
buffer.setLength(0);
if (localName.equals("Tables"))
data_list = new ArrayList<Table_Beans>();
else if (localName.equals("Table"))
data = new Table_Beans();
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("TeamIDGiven"))
data.setTeamIDGiven(buffer.toString().trim());
else if (localName.equalsIgnoreCase("City"))
data.setCity(buffer.toString().trim());
else if (localName.equalsIgnoreCase("TeamName"))
data.setTeamName(buffer.toString().trim());
else if (localName.equalsIgnoreCase("Table"))
data_list.add(data);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
buffer.append(ch, start, length);
}
}
以下の主な活動。
public class Test1 extends Activity {
private ArrayList<Table_Beans> data1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getData();
}
private void getData() {
try {
InputSource inSource = new InputSource(getResources()
.openRawResource(R.raw.abc));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
TestXMLhandler xmlhandler1 = new TestXMLhandler();
xr.setContentHandler(xmlhandler1);
xr.parse(inSource);
data1 = xmlhandler1.getData();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
ここでdata1を確認してください。Cityが空白であることがわかりました。すべて動作しています。