6.2.7.5
Collecting Unspecified Attributes: XmlAnyAttribute
An XML element may carry attributes which aren't defined in the
XML schema, or have no explicit mapping to some field in the Java
class defining the element type. It's possible to collect these
unspecified attributes into a map with the type
Map<QName,Object>
. Here is an example using the
annotation XmlAnyAttribute
:
public class MixtureType {
private Map<QName,Object> any;
private String title;
public MixtureType(){}
@XmlAnyAttribute
public Map<QName,Object> getAny(){
if( any == null ){
any = new HashMap<QName,Object>();
}
return any;
}
@XmlElement
public String getTitle(){
return title;
}
public void setTitle( String value ){
title = value;
}
}
Let's assume that the top level element of type DocumentType
contains nothing but one MixtureType
element. Then, an XML data
file that can be unmarshalled into an object of this class would look like
this:
<document>
<mixture foo="a foo attribute" bar="attribute of bar">
<title>A mixture of elements</title>
</mixture>
</document>
After unmarshalling this into a DocumentType
object, the
sub-element and its spurious attributes can be extracted like this:
JAXBElement<DocumentType> jbe =
(JAXBElement)u.unmarshal( new File( "mixture.xml" ) );
DocumentType doc = jbe.getValue();
MixtureType mix = doc.getMixture();
System.out.println( "Title: " + mix.getTitle() );
Map<QName,Object> amap = mix.getAny();
for( Map.Entry<QName,Object> e: amap.entrySet() ){
System.out.println( e.getKey() + "=\"" + e.getValue() + "\"" );
}
This is the resulting output:
A mixture of elements
foo="a foo attribute"
bar="attribute of bar"