我想使用XML
解组下面的JAXB
,以便可以导航到子节点以读取叶子标签元素。
<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>
我希望有1个父母和2个父母的孩子数量。
答案 0 :(得分:0)
您需要构建模型,使用JAXB
批注进行注释并解析给定的XML
。参见以下示例:
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(c -> System.out.println(c.getName() + " => " + c.getConcept().size()));
}
}
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
class Roots {
private Concept concept;
// getters, setters
}
@XmlType(name = "concept")
@XmlAccessorType(XmlAccessType.FIELD)
class Concept {
@XmlAttribute
private String name;
@XmlElement
private List<Concept> concept;
// getters, setters
}
上面的代码显示:
Parent1 : 2
Parent2 : 2