[英]How can I create Generics for XML Parsing?
I currently using jsoup and sometimes dom4j for parsing string of xml. 我目前使用jsoup,有时使用dom4j来解析xml字符串。 Here's an example on how I do it using jsoup.
这是一个有关如何使用jsoup的示例。
Document doc = Jsoup.parse(xml);
Elements root = doc.select("person");
for(Elements elem : elements){
Person person = new Person();
person.setFirstname(elem.select("firstName").text());
person.setLastname(elem.select("lastName").text());
person.setAddress(elem.select("address").text());
//other setters here
}
Everytime I have to parse xml I have to get all elements and set to setters of POJO. 每次我必须解析xml时,都必须获取所有元素并将其设置为POJO的设置器。 Now I want to create a Generics where I only have to do is to passed a string of xml and a class of POJO then it will set all the values of fields based on all the elements of xml.
现在,我想创建一个泛型,只需传递一个xml字符串和一个POJO类,然后它将基于xml的所有元素设置字段的所有值。 How can I do it?
我该怎么做? Any ideas?
有任何想法吗?
Thanks in advance. 提前致谢。
JAXB is the way to go. JAXB是必经之路。
Note: It is included in JAVA 1.6 and later versions 注意:它包含在JAVA 1.6和更高版本中
Add XML tags to your POJO (XmlRootElement is enough for simple objects, XmlElement can also be added to variables) 将XML标记添加到POJO(XmlRootElement对于简单对象已经足够,XmlElement也可以添加到变量中)
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Person")
public class Person {
private String firstName;
private String lastName;
private String address;
public final String getFirstName() {
return firstName;
}
public final void setFirstName(String firstName) {
this.firstName = firstName;
}
public final String getLastName() {
return lastName;
}
public final void setLastName(String lastName) {
this.lastName = lastName;
}
public final String getAddress() {
return address;
}
public final void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "FirstName: " + firstName + " LastName: " + lastName + " Address: " + address;
}
}
Use Unmarshaller to create the POJO from the xml file. 使用Unmarshaller从xml文件创建POJO。
File file = new File("<Path to Xml file>");
JAXBContext context = JAXBContext.newInstance(Person.class);
Unmarshaller unmarsheller = context.createUnmarshaller();
Person person = (Person) unmarsheller.unmarshal(file);
System.out.println(person);
You can use Marshaller to create the XML from the POJO also. 您也可以使用Marshaller从POJO创建XML。
There are more examples available here to create complex objects, add lists, arrays. 还有更多可用的例子在这里创建复杂的对象,添加列表,数组。
Note: It is not available in Android Platform, If you want to use it on android you can use SimpleXML with almost same implementation 注意:它在Android平台中不可用,如果您想在android上使用它,则可以使用具有几乎相同实现的SimpleXML
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.