如何使用JAXB解析Java中的XML?

如何使用JAXB解析Java中的XML?,第1张

如何使用JAXB解析Java中的XML?

您可以执行以下 *** 作。通过利用,

@XmlElementWrapper
您可以减少所需的类数量:

福斯特之家

package nov18;import java.util.List;import javax.xml.bind.annotation.*;@XmlRootElement(name="FosterHome")@XmlAccessorType(XmlAccessType.FIELD)public class FosterHome {    @XmlElement(name="Orphanage")    private String orphanage;    @XmlElement(name="Location")    private String location;    @XmlElementWrapper(name="Families")    @XmlElement(name="Family")    private List<Family> families;    @XmlElementWrapper(name="RemainingChildList")    @XmlElement(name="ChildID")    private List<String> remainingChildren;}

家庭

package nov18;import java.util.List;   import javax.xml.bind.annotation.*;@XmlAccessorType(XmlAccessType.FIELD)public class Family {    @XmlElement(name="ParentID")    private String parentID;    @XmlElementWrapper(name="ChildList")    @XmlElement(name="ChildID")    private List<String> childList;}

演示版

package nov18;import java.io.File;import javax.xml.bind.*;public class Demo {    public static void main(String[] args) throws Exception {        JAXBContext jc = JAXBContext.newInstance(FosterHome.class);        Unmarshaller unmarshaller = jc.createUnmarshaller();        FosterHome fosterHome = (FosterHome) unmarshaller.unmarshal(new File("src/nov18/input.xml"));        Marshaller marshaller = jc.createMarshaller();        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        marshaller.marshal(fosterHome, System.out);    }}

输入输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><FosterHome>    <Orphanage>Happy Days Daycare</Orphanage>    <Location>Apple Street</Location>    <Families>        <Family> <ParentID>Adams</ParentID> <ChildList>     <ChildID>Child1</ChildID>     <ChildID>Child2</ChildID> </ChildList>        </Family>        <Family> <ParentID>Adams</ParentID> <ChildList>     <ChildID>Child3</ChildID>     <ChildID>Child4</ChildID> </ChildList>        </Family>    </Families>    <RemainingChildList>        <ChildID>Child5</ChildID>        <ChildID>Child6</ChildID>    </RemainingChildList></FosterHome>

想要查询更多的信息

  • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html

更新

有没有简单的方法可以迭代/打印出Family类中的所有ChildID?

您可以执行以下 *** 作:

    for(Family family : fosterHome.getFamilies()) {        System.out.println(family.getParentID());        for(String childID : family.getChildList()) { System.out.println("    " + childID);        }    }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5505983.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存