我有一个XML格式,如下所示:
<list>12
<item name="a">
<child parent="b" age="1">David Beckham</child>
</item>
</list>
问题是如何使用JAXB提取12?哪个注释支持它?非常感谢。
最佳答案
以下是工作示例。
import java.io.StringReader;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.transform.stream.StreamSource;
public class TestJAXBMixed {
public static void main(String[] args) throws Exception {
final String str =
"<list>12<item name=\"a\"><child parent=\"b\" age=\"1\">David Beckham</child></item></list>";
final JAXBContext jaxbContext = JAXBContext.newInstance(Child.class, Item.class, ListElement.class);
final JAXBElement<ListElement> obj = jaxbContext.createUnmarshaller().unmarshal(new StreamSource(new StringReader(str)), ListElement.class);
// The following is an array of objects representing the <list> content in order,
// i.e. it is a sequence of a String (12) and an Object (Item)
final List<Object> content = obj.getValue().getContent();
System.out.println(content);
}
}
@XmlRootElement(name="child")
class Child {
private String parent;
private String age;
private String text;
public String getParent() {
return parent;
}
@XmlAttribute(name="parent")
public void setParent(String parent) {
this.parent = parent;
}
public String getAge() {
return age;
}
@XmlAttribute(name="age")
public void setAge(String age) {
this.age = age;
}
public String getText() {
return text;
}
@XmlValue
public void setText(String text) {
this.text = text;
}
}
@XmlRootElement(name="item")
class Item {
private String name;
private Child child;
public String getName() {
return name;
}
@XmlAttribute(name="name")
public void setName(String name) {
this.name = name;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
@XmlRootElement(name="list")
class ListElement {
private List<Object> content;
public List<Object> getContent() {
return content;
}
@XmlMixed
@XmlElementRefs({
@XmlElementRef(name="item", type=Item.class)
})
public void setContent(List<Object> content) {
this.content = content;
}
}
关于java - 如何使用jaxb在XML格式的标签之间获取值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50469889/