[英]Unmarshal JAXB elements with same tag as in parent and child
I want to unmarshall the below XML
using JAXB
, so that I can navigate to child node to read the leaf tag element. 我想使用
JAXB
解组下面的XML
,以便我可以导航到子节点以读取叶标记元素。
<root>
<concept name="GrandParent">
<concept name="Parent1">
<concept name="Child11">
<input>some child input11</input>
</concept>
<concept name="Child12">
<input>some child input21</input>
</concept>
</concept>
<concept name="Parent2">
<concept name="Child21">
<input>some child input21</input>
</concept>
<concept name="Child22">
<input>some child input22</input>
</concept>
</concept>
</concept>
</root>
I would expect number of children for parent1 and parent 2. 我期望parent1和parent2的子女数量。
You need to build model, annotate with JAXB
annotations and parse given XML
. 您需要构建模型,使用
JAXB
注释进行批注并解析给定的XML
。 See below example: 见下面的例子:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.File;
import java.util.List;
public class XmlMapperApp {
public static void main(String[] args) throws Exception {
File xmlFile = new File("./resource/test.xml").getAbsoluteFile();
JAXBContext jaxbContext = JAXBContext.newInstance(Roots.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Concept root = ((Roots) unmarshaller.unmarshal(xmlFile)).getConcept();
root.getConcept().forEach(System.out::println);
}
}
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
class Roots {
private Concept concept;
// getters, setters, toString
}
@XmlType(name = "concept")
@XmlAccessorType(XmlAccessType.FIELD)
class Concept {
@XmlAttribute
private String name;
@XmlElement
private List<Concept> concept;
@XmlElement
private String input;
// getters, setters, toString
}
Above code prints: 上面的代码打印:
Concept{name='Parent1', concept=[Concept{name='Child11', concept=null, input='some child input11'}, Concept{name='Child12', concept=null, input='some child input21'}], input='null'}
Concept{name='Parent2', concept=[Concept{name='Child21', concept=null, input='some child input21'}, Concept{name='Child22', concept=null, input='some child input22'}], input='null'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.