我必须将xml文件转换为数组列表,但我不知道如何。 这就是我的xml文件的样子。
window
我的数组列表由Contact类构成,如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<data>
<record>
<name> abc </name>
<email> abc@abc </email>
</record>
<record>
<name> asd </name>
<email> asd@asd </email>
</record>
.
.
.
</data>
答案 0 :(得分:1)
您可以使用JAXB ... Unmarshling将xml转换为java对象
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<Question>
<id>1</id>
<Question>
....
.....
Question.java
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Question {
private int id;
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
主要方法
try {
File file = new File("question.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Question.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Question que= (Question) jaxbUnmarshaller.unmarshal(file);
System.out.println(que.getId());
System.out.println("Answers:");
List<Answer> list=que.getAnswers();
for(Answer ans:list)
System.out.println(ans.getId());
} catch (JAXBException e) {
e.printStackTrace();
}
将XML文档转换为java对象的步骤。
1.Create POJO or bind the schema and generate the classes.
2.Create the JAXBContext object.
3.Create the Unmarshaller objects.
4.Call the unmarshal method.
5.Use getter methods of POJO to access the data.
答案 1 :(得分:0)
这就是我实际做到的方式。 这可能对将来的某些人有所帮助。
private ArrayList<Contact> parse() throws XmlPullParserException,IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
AssetManager assetManager = getAssets();
parser.setInput(getAssets().open("myxml.xml"),null);
ArrayList<Contact> Contacts = null;
int eventType = parser.getEventType();
Contact con = null;
while (eventType != XmlPullParser.END_DOCUMENT){
String name;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
Contacts = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equals("record"))
con = new Contact();
else if (con != null){
if (name.equals("name"))
con.name = parser.nextText();
else if (name.equals("email"))
con.email= parser.nextText();
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("record") && con != null)
Contacts.add(con);
}
eventType = parser.next();
}
return Contacts;
}`