爲此,我將利用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);
}
}
詳細請? – Navi 2011-01-21 11:19:46
沒有問號......我也無法確定它會在你的文章中的位置。 – aioobe 2011-01-21 11:19:58