JAXB – 如何使用Map中的属性创建XML元素?

我需要这样的东西 –

     ....   

我有Map for LowLevel元素,我希望像上面的XML一样填充其条目。 使用JAXB封装/绑定它的方法是什么?

您可以使用自定义适配器。 例

 //Token.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlRootElement class LowLevelToken { @XmlAttribute(name = "info-key") public String key; @XmlAttribute(name = "info-value") public String value; private LowLevelToken() {} public LowLevelToken(String key, String value) { this.key = key; this.value = value; } } @XmlRootElement class HighLevelToken { @XmlAttribute(name = "info-1") public String info1; @XmlAttribute(name = "info-2") public String info2; private HighLevelToken() {} public HighLevelToken(String info1, String info2) { this.info1 = info1; this.info2 = info2; } } class TokenWrapper { @XmlElement(name="LowLevel") public List tokens = new ArrayList(); } class TokenAdapter extends XmlAdapter> { @Override public TokenWrapper marshal(Map lowlevelTokens) throws Exception { TokenWrapper wrapper = new TokenWrapper(); List elements = new ArrayList(); for (Map.Entry property : lowlevelTokens.entrySet()) { elements.add(new LowLevelToken(property.getKey(), property.getValue())); } wrapper.tokens = elements; return wrapper; } @Override public Map unmarshal(TokenWrapper tokenWrapper) throws Exception { Map tokens = null; if(tokenWrapper != null && tokenWrapper.tokens != null && !tokenWrapper.tokens.isEmpty()){ tokens = new HashMap(); for(LowLevelToken token : tokenWrapper.tokens){ tokens.put(token.key, token.value); } } return tokens; } } @XmlRootElement(name = "Token") public class Token { HighLevelToken highLevel; Map lowLevel; public HighLevelToken getHighLevel() { return highLevel; } @XmlElement(name = "HighLevel") public void setHighLevel(HighLevelToken highLevel) { this.highLevel = highLevel; } public Map getLowLevel() { return lowLevel; } @XmlElement(name = "LowLevel") @XmlJavaTypeAdapter(TokenAdapter.class) public void setLowLevel(Map lowLevel) { this.lowLevel = lowLevel; } } 

一个示例程序

 import java.util.HashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JAXBExample { public static void main(String[] args) { Token token = new Token(); token.setHighLevel(new HighLevelToken("1", "2")); token.setLowLevel(new HashMap() {{ put("LK1", "LV1"); put("LK2", "LV2"); put("LK2", "LV2"); }}); try { JAXBContext jaxbContext = JAXBContext.newInstance(Token.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(token, System.out); } catch (JAXBException e) { e.printStackTrace(); } } } 

这会产生