gpt4 book ai didi

java - 解码具有与父级和子级相同标记的 JAXB 元素

转载 作者:行者123 更新时间:2023-12-02 04:59:46 24 4
gpt4 key购买 nike

我想使用 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>

我预计父级 1 和父级 2 的子级数量。

最佳答案

您需要构建模型,使用 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(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
}

上面的代码打印:

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'}

关于java - 解码具有与父级和子级相同标记的 JAXB 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56392446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com