我一直在尝试从 XML 中提取子节点,该 XML 是我从 SOAP 作为字符串收到的。我可以检索父节点,但无法检索子节点。我也上网看看是否能得到答案,但都无济于事。我看到了一些直接子拉动的例子,但这并没有解决我的问题。
<response>
<code>1</code>
<list available="2">
<cart id="2" name="egg">
<stuff>
<id>001</id>
<name>Crew</name>
<shortname>C</shortname>
</stuff>
</cart>
<cart id="4" name="bread">
<stuff>
<id>004</id>
<name>Bread</name>
<shortname>B</shortname>
</stuff>
</cart>
</list>
</response>
响应类
public class Response {
private String code;
private String list;
private String cart;
private Response.Stuff stuffs;
@XmlElement(name="code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
.
.
@XmlElement
public Response.Stuff getStuff() {
return this.stuffs;
}
public void setStuff(Response.Cart stuff) {
this.stuffs = stuff;
}
public static class Stuff {
private List<Stuff> stuff;
public List<Stuff> getStuff() {
if (stuff == null) {
stuff = new ArrayList<Stuff>();
}
return stuff;
}
}
}
东西类
public class Stuff {
private String id;
private String crew;
@XmlElement
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
.
.
}
现在我的问题是如何使用 JAXB 提取子内容(即 id、名称和短名称)。 我创建了 Response 和 Stuff 类,并在响应中创建了一个列表,但是当我运行代码时,它会抛出 null 异常。
PS:请记住 XML 不是文件,它是字符串,并且正在使用 StringReader
类作为 JAXB.unmarshal
最佳答案
JAXBContext jcontext= JAXBContext.newInstance();
unmarshaller um=jcontext.createUnmarshaller();
JAXBElement je=um.unmarshal(new File("传递xml文件位置"));
响应 r= getValue();
r.getlist().getcart().getstuff().getid().getValue();
尝试一下这个可能会起作用
关于java - 使用 JAXB 将 XML 子内部节点从 XML 拉到 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30869299/