2011-01-21 67 views
0

使用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> 
+0

詳細請? – Navi 2011-01-21 11:19:46

+1

沒有問號......我也無法確定它會在你的文章中的位置。 – aioobe 2011-01-21 11:19:58

回答

1

爲此,我將利用unmarshal事件來存儲Mobile對象列表中的信息到Map中。

你的域模型將如下所示:

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

} 
相關問題