java xml jaxb,如何使用JAXB在Java中解析此XML?

I have the following XML, no XSD or schema with it that I want to parse to java object(s) using JAXB as I heard its better than SAX. Is there a way to accomplish this with annotations or a better way to do this? Does it make it so that i just need a single FosterHome class? I am having trouble finding how to do this any help is grateful.

I was originally thinking of having a FosterHome, Family, and Child class. Using JAXB, is having 3 classes no longer necessary? Im not sure how to deal with this as ChildID shows up in two different areas.

Happy Days Daycare

Apple Street

Adams

Child1

Child2

Adams

Child3

Child4

Child5

Child6

解决方案

You could do the following. By leveraging @XmlElementWrapper you can reduce the amount of classes that you require:

FosterHome

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 families;

@XmlElementWrapper(name="RemainingChildList")

@XmlElement(name="ChildID")

private List remainingChildren;

}

Family

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 childList;

}

Demo

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);

}

}

Input/Output

Happy Days Daycare

Apple Street

Adams

Child1

Child2

Adams

Child3

Child4

Child5

Child6

For More Information

UPDATE

Is there I easy way I can iterate/print out all the ChildID in the

Family class?

You could do the following:

for(Family family : fosterHome.getFamilies()) {

System.out.println(family.getParentID());

for(String childID : family.getChildList()) {

System.out.println(" " + childID);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值