我想獲得xml文件的值。如何獲取xml標籤中的值?
<p1>
<cts>Pq44</cts>
<cts>qw44</cts>
</p1>
P1.JAVA
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class P1 {
private List<Cts> cts;
public P1() {
cts = new ArrayList<cts>();
}
public List<cts> getcts() {
return cts;
}
public void setcts(List<cts> cts) {
this.cts = cts;
}
}
CTS.JAVA
public class CTS {
private String ct;
// Getter and setter for ct.
}
我Main.java
try {
File file = new File("D:\\Bye.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(P1.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
P1 p = (P1) jaxbUnmarshaller.unmarshal(file);
List<CTS> cts = p.getCTS();
// Size of list coming right `2`
for (CTS c : cts) {
System.out.println(CTS2.getCT());
}
} catch (JAXBException e) {
e.printStackTrace();
}
當我運行main.java,它打印:
null
null
你不需要做你的解決方法。通過利用'@ XmlValue'註釋,您可以使用您的問題中的對象模型:http://stackoverflow.com/a/13989888/383861 –