How to use hashmap properties with JAXB?

I have been catching JAXB for some time now, I need to create xml as below

<Root attr1="" attr2="" .. attrn="" > <CNode attr1="" attr2="" /> . . . <CNode .. /> </Root> 

The attributes of the Root element are dynamic and will come either from the properties file or from the template. What is the best way to get it in a structure as shown above? I use hashmaps for dynamic variables and then tried to map it to XmlJavaTypeAdapter, the best I could do was

 <Root> <Attribs> <entry key="attr1">Value</entry> </Attribs> <CNode .. /> </Root> 

Is there a way in jaxb to say that to use the hashmap key as the attribute name and the value for this key as the value for this attribute in xml? Or, if you think that there is a better way to do this, I am open to suggestions. I am thinking of using jaxb marshaller to add the root node separately. However, it would be better if I could just use the jaxb adapter. Thanks!

+6
java hashmap jaxb
source share
1 answer

@XmlAnyAttribute matches what you need:

Root

 import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.namespace.QName; @XmlRootElement(name="Root") public class Root { private Map<QName, String> extension; private List<CNode> cnodes; @XmlAnyAttribute public Map<QName, String> getExtension() { return extension; } public void setExtension(Map<QName, String> extension) { this.extension = extension; } @XmlElement(name="CNode") public List<CNode> getCnodes() { return cnodes; } public void setCnodes(List<CNode> cnodes) { this.cnodes = cnodes; } } 

CNode

 import java.util.Map; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.namespace.QName; public class CNode { private Map<QName, String> extension; @XmlAnyAttribute public Map<QName, String> getExtension() { return extension; } public void setExtension(Map<QName, String> extension) { this.extension = extension; } } 

Demo

 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(Root.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); Root root = (Root) unmarshaller.unmarshal(new File("input.xml")); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } } 

Input.xml

 <?xml version="1.0" encoding="UTF-8"?> <Root att1="A" att2="B"> <CNode att3="C" att4="D"/> <CNode att5="E" att6="F"/> </Root> 
+6
source share

All Articles