我正在一个需要使用JAXB解析XML文件的项目中。下面是示例XML:
<FirstLevel>
<Second>
<Third>
<ProductName>Computer</ProductName>
</Third>
</Second>
<Second>
<Third>
<ProductName>Mobile</ProductName>
</Third>
</Second>
</FirstLevel>
我只需要产品名称。为了做到这一点,我尝试了以下方法,但没有成功:
@XmlRootElement(name="FirstLevel")
public class DTOClass {
private String productName;
public String getProductName() {
return productName;
}
@XmlElement(name="ProductName")
public void setProductName(String productName) {
this.productName = productName;
}
}
但这可行:
@XmlRootElement(name="FirstLevel")
public class DTOClass {
private List<Second> second;
public List<Second> getSecond() {
return second;
}
@XmlElement(name="Second")
public void setSecond(List<Second> second) {
this.second = second;
}
static class Second{
private Third third;
public Third getThird() {
return third;
}
@XmlElement(name="Third")
public void setThird(Third third) {
this.third = third;
}
static class Third{
private String productName;
public String getProductName() {
return productName;
}
@XmlElement(name="ProductName")
public void setProductName(String productName) {
this.productName = productName;
}
}
}
}
我的问题是
是否需要为每个级别的内部类创建一个或多个内部类? XML来解析XML(如第二个XML)?
在java类中是否只有某些字段是 需要(像第一个一样)?