<MenuByRole InstanceID="519" RoleID="614">
<MainMenu Id="2298">Home</MainMenu>
<MainMenu Id="2431">My Results</MainMenu>
<MainMenu Id="2415">My Attendance</MainMenu>
</MenuByRole>
这是我的 XML 文件,我已经检索了此 XML 文件中的所有 ID 值。这是以下代码,
if (qName.equalsIgnoreCase("MainMenu"))
{
id = attributes.getValue("Id");
MainMenu = true;
}
但是我想根据名称检索特定的 Id 值。例如我想在这里借助家庭名称检索 ID 值 2298
下面是
完整的解析代码。您将获得listMenuId
的所有ID和listMenuName
的所有姓名
String currentValue = "";
String currentTag = "";
ArrayList<String> listMenuId;
ArrayList<String> listMenuName;
// Called when tag starts
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
currentTag = localName;
if(currentTag.equalsIgnoreCase("MenuByRole")){
listMenuId = new ArrayList<String>();
listMenuName = new ArrayList<String>();
}
if(currentTag.equalsIgnoreCase("MainMenu")){
listMenuId.add(attributes.getValue("Id"));
}
}
// Called when tag closing
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
// Called to get tag characters
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
currentValue = currentValue + new String(ch, start, length);
if(currentTag.equalsIgnoreCase("MainMenu"))
listMenuId.add(currentValue);
}
}
public class MainMenu {
private Long id;
private String Name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
ArrayList<MainMenu> munuIDList;
MainMenu oMainMenu;
boolean isReadData;
String sName;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase("MenuByRole")){
munuIDList = new ArrayList<MainMenu>();
isReadData = false;
}
if(localName.equalsIgnoreCase("MainMenu")){
isReadData = true;
oMainMenu = new MainMenu();
oMainMenu.setId(attributes.getValue("Id"));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase("MainMenu"))
oMainMenu.setName(sName);
sName = null;
isReadData = false;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(isReadData) {
sName = new String(ch, start, length);
}
}
MainActivity
public class MainActivity extends Activity implements OnItemClickListener{
ArrayLsit<MainMenu> lstMainMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myListView = (ListView) findViewById(R.id.myListView);
myListView.setOnItemClickListener(this);
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, lstMainMenu.get(arg2).getId(), Toast.LENGTH_SHORT).show();
}