我有这个XML文件,我将其解析为ArrayList
在这个ArrayList中,我有一些国家和其中的国家的警报号。
我想搜索一个国家,然后选择警察,救护车或救火车。数。
这是帮助您的代码。
将XML解析为ArrayList:
protected ArrayList<Alarmdiensten> getAlarmdiensten() {
ArrayList<Alarmdiensten> lijst = new ArrayList<Alarmdiensten>();
try {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i=0;i<nl.getLength();i++) {
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.land = Xml.innerHtml(Xml.getChildByTagName(node, "naam"));
land.landcode = Xml.innerHtml(Xml.getChildByTagName(node, "code"));
land.politie = Xml.innerHtml(Xml.getChildByTagName(node, "politie"));
land.ambulance = Xml.innerHtml(Xml.getChildByTagName(node, "ambulance"));
land.brandweer = Xml.innerHtml(Xml.getChildByTagName(node, "brandweer"));
land.telamba = Xml.innerHtml(Xml.getChildByTagName(node, "telamba"));
land.adresamba = Xml.innerHtml(Xml.getChildByTagName(node, "adresamba"));
lijst.add(land);
}
} catch (Exception e) {;
}
return lijst;
}
使用警报编号的方法:
public void AlarmMenu(){
String landcode;
ArrayList<Alarmdiensten> diensten = getAlarmdiensten();
if(fakelocation = true) {
landcode = sfakelocation;
}
else {
try {
landcode = getAddressForLocation(this, locationNow).getCountryCode();
} catch (IOException e) {
e.printStackTrace();
}
}
因此,我有了区号,并且我想在ArrayList中搜索属于该区号的数字。
我怎样才能做到这一点?
最佳答案
好了,现在您有了一个Alarmdiensten对象的ArrayList。我建议您将其更改为“地图”,以便存储“地区代码地图”与“ Alarmdiensten”对象。
这样,您就可以使用陆域代码将Alarmdiensten从地图中删除,然后只需在Alarmdiensten对象上调用getPolitie()等方法。
我要确保您封装了Alarmdiensten对象BTW,直接访问它的私有成员有点不行:)
所以像这样:
protected Map<String, Alarmdiensten> getAlarmdiensten()
{
Map<String, Alarmdiensten> alarmNumbersForCountries
= new HashMap<String, Alarmdiensten>();
try
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i = 0; i < nl.getLength(); i++)
{
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.setLand(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
land.setLandcode(Xml.innerHtml(Xml.getChildByTagName(node, "code")));
land.setPolitie(Xml.innerHtml(Xml.getChildByTagName(node, "politie")));
land.setAmbulance(Xml.innerHtml(Xml.getChildByTagName(node, "ambulance")));
land.setBrandweer(Xml.innerHtml(Xml.getChildByTagName(node, "brandweer")));
land.setTelamba(Xml.innerHtml(Xml.getChildByTagName(node, "telamba")));
land.setAdresamba(Xml.innerHtml(Xml.getChildByTagName(node, "adresamba")));
alarmNumbersForCountries.put(land.getLandCode(), land);
}
}
catch (Exception e)
{
// Handle Exception
}
return alarmNumbersForCountries;
}
将条目从地图中取出
Alarmdiensten land = alarmNumbersForCountries.get(landcode);
YMMV的另一点是,您可能希望从XML解析中拆分用于构建Alarmdiensten对象的方法部分。 “每种方法都应该做好一件事情,一件事情要做好。”