JAXB和List属性可通过Key访问

时间:2011-01-21 11:17:37

标签: java jaxb

使用JAXB如何将此文档解组为允许我按手机号码查询用户名的对象模型?

<Details>
    <Mobile>
        <Username>Rahul</Username>
        <MobileNumber>7539518520</MobileNumber>
    </Mobile>
    <Mobile>
        <Username>Rahul</Username>
        <MobileNumber>1234567890</MobileNumber>
    </Mobile>
    <Mobile>
        <Username>Kumar</Username>
        <MobileNumber>7894561230</MobileNumber>
    </Mobile>
</Details>

1 个答案:

答案 0 :(得分:1)

为此,我将利用unmarshal事件来存储Map中Mobile对象列表中的信息。

您的域名模型如下:

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Details")
@XmlAccessorType(XmlAccessType.NONE)
public class Details {

    private Map<String, String> mobileNumberToUsername;

    @XmlElement(name="Mobile")
    private List<Mobile> mobileList;

    public Details() {
        mobileNumberToUsername = new HashMap<String, String>();
    }

    public String getUsername(String mobileNumber) {
        return mobileNumberToUsername.get(mobileNumber);
    }

    void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
        for(Mobile mobile : mobileList) {
            mobileNumberToUsername.put(mobile.getMobileNumber(), mobile.getUsername());
        }
    }

}

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlType(propOrder={"username", "mobileNumber"})
public class Mobile {

    private String username;
    private String mobileNumber;

    @XmlElement(name="Username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @XmlElement(name="MobileNumber")
    public String getMobileNumber() {
        return mobileNumber;
    }

    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }

}

您可以使用XML文档和以下演示代码测试此映射:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Details.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum121/input.xml");
        Details details = (Details) unmarshaller.unmarshal(xml);

        System.out.println(details.getUsername("1234567890"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(details, System.out);
    }

}