【发布时间】:2013-11-25 05:35:49
【问题描述】:
这里我必须使用 SAX Parser 来解析 xml 文件,我已经完全解析过了。下面是我的xml文件。
category.xml
<main>
<category>
<id>1</id>
<item>hey whats up?</item>
</category>
<category>
<id>2</id>
<item>Hello !!</item>
</category>
<category>
<id>3</id>
<item>Good Morning.</item>
</category>
</main>
但现在我想根据 id 解析其他 xml 文件。说当用户点击项目“嘿,怎么了?” id=1,应该显示其他xml文件中id=1的数据(这里的数据是“一”和“二”)。
second.xml
<main>
<category>
<id>1</id>
<item>one</item>
<item>two</item>
</category>
<category>
<id>2</id>
<item>three</item>
<item>four</item>
</category>
</main>
以下是我的 .java 类。
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Employee> employees;
private String tempVal;
private Employee tempEmp;
public SAXXMLHandler() {
employees = new ArrayList<Employee>();
}
public List<Employee> getEmployees() {
return employees;
}
// Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
// reset
tempVal = "";
if (qName.equalsIgnoreCase("category"))
{
// create a new instance of employee
tempEmp = new Employee();
}
}
public void characters(char[] ch, int start, int length) throws SAXException
{
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
if (qName.equalsIgnoreCase("category"))
{
// add it to the list
employees.add(tempEmp);
}
else if (qName.equalsIgnoreCase("item"))
{
tempEmp.setItem(tempVal);
}
else if (qName.equalsIgnoreCase("id"))
{
tempEmp.setId(Integer.parseInt(tempVal));
}
}
}
Employee.java
public class Employee {
private String item;
private int id;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return item + ": " + id;
}
public String getDetails() {
String result = "Id" + ": " + id + "\n" ;
return result;
}
}
SAXParserActivity.java
public class SAXParserActivity extends Activity {
Button button, btnAdd;
ListView lv;
List<Employee> employees = null;
EditText et;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.spinner);
try
{
employees = SAXXMLParser.parse(getAssets().open("XML/category.xml"));
ArrayAdapter<Employee> adapter = new ArrayAdapter<Employee>(this, R.layout.list_item, employees);
lv.setAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
}
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos,
long arg3) {
Employee employee = (Employee) parent.getItemAtPosition(pos);
Toast.makeText(parent.getContext(), employee.getDetails(),
Toast.LENGTH_LONG).show();
}
});
}
}
如何根据用户选择解析第二个 xml 文件?
【问题讨论】:
-
您需要编写服务,以便它接收选择的用户 ID 作为参数并将该用户的详细信息作为 xml 返回
-
@PramodJGeorge:好的,你能给我举几个例子吗?
-
我手头没有例子,但这个想法会奏效。