我的目标是使用此XML
<data>
<description lang="de">Deutscher Text</description>
<description lang="en">english text</description>
</data>
此类型:
@XmlAccessorType( XmlAccessType.FIELD )
@XmlRootElement
@XmlSeeAlso( {
Description.class
} )
public class Data
{
@XmlElement( name = "description" )
@XmlJavaTypeAdapter( LanguageAdapter.class )
Map<String, String> descriptions = new HashMap<>();
}
使用以下XMLAdapter和中间类型:
@XmlAccessorType( XmlAccessType.FIELD )
@XmlRootElement
public class Description
{
@XmlAttribute
String lang;
@XmlValue
String value;
public Description( String lang, String value )
{
this.lang = lang;
this.value = value;
}
public Description()
{}
}
// import static java.util.Arrays.stream;
// import static java.util.stream.Collectors.toMap;
public class LanguageAdapter extends XmlAdapter<Description[], Map<String, String>>
{
@Override
public Map<String, String> unmarshal( Description[] v ) throws Exception
{
return stream( v )
.collect( toMap( Description::getLang, Description::getValue ) );
}
@Override
public Description[] marshal( Map<String, String> v ) throws Exception
{
return v.entrySet().stream()
.map( e -> new Description( e.getKey(), e.getValue() ) )
.toArray( Description[]::new );
}
}
不幸的是,地图未填充,将数据结构编组会产生以下xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
<description>
<item lang="de">deutsch</item>
<item lang="en">english</item>
</description>
</data>
有没有办法解决这个问题?