我有一个从Apache Commons Configuration扩展CompositeConfiguration类的类。我正在尝试使用MOXy将其编组为XML。我创建了一个XML适配器,将配置转换为简单名称/值对象列表。
我尝试过对下面的内容进行多种修改,但仍然受到了阻碍。我可以在创建JAXB上下文时看到我的适配器类被加载和实例化,但是当我编组配置对象时它永远不会被调用。
查看MOXy源代码,我开始怀疑无法为同时也是根元素的Java类指定XML适配器。我是否正确地开始工作,或者采用完全不同的方式来做到这一点?
XML适配器:
public class JAXBConfigurationAdapter extends XmlAdapter<Object, BetterBaseConfiguration>
{
@Override
public Object marshal(final BetterBaseConfiguration javaObject) throws Exception
{
List<ConfigurationPropertyXmlType> jaxbConfiguration = new ArrayList<>();
Iterator<String> keys = javaObject.getKeys();
while (keys.hasNext())
{
String key = keys.next();
ConfigurationPropertyXmlType property = new ConfigurationPropertyXmlType();
property.setKey(key);
property.setValue(javaObject.getString(key));
jaxbConfiguration.add(property);
}
return jaxbConfiguration;
}
@Override
public CompositeConfiguration unmarshal(final Object jaxbObject) throws Exception
{
BetterBaseConfiguration configuration = new BetterBaseConfiguration();
for (ConfigurationPropertyXmlType property : (List<ConfigurationPropertyXmlType>) jaxbObject)
{
configuration.setProperty(property.getKey(), property.getValue());
}
return configuration;
}
}
名称/价值类:
public class ConfigurationPropertyXmlType
{
private String key;
private String value;
public String getKey()
{
return key;
}
public String getValue()
{
return value;
}
public void setKey(final String key)
{
this.key = key;
}
public void setValue(final String value)
{
this.value = value;
}
}
EclipseLink映射文件:
<?xml version="1.0" encoding="UTF-8"?>
<xml-bindings version="2.5" xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.eclipse.org/eclipselink/xsds/persistence/oxm http://www.eclipse.org/eclipselink/xsds/eclipselink_oxm_2_5.xsd"
package-name="myapp.configuration">
<xml-schema element-form-default="QUALIFIED">
<xml-ns prefix="mynm" namespace-uri="http://mynamespace" />
</xml-schema>
<java-types>
<java-type name="myapp.configuration.BetterBaseConfiguration" >
<xml-java-type-adapter value="myapp.configuration.JAXBConfigurationAdapter" type="myapp.configuration.BetterBaseConfiguration" />
<xml-root-element name="Configuration" />
</java-type>
</java-types>
</xml-bindings>
期望的输出:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property>
<name>some name</name>
<value>some value</value>
</property>
</configuration>
答案 0 :(得分:2)
EclipseLink MOXy和其他JAXB (JSR-222)个提供程序不会将XmlAdapter
应用于正在编组的根对象。您可以在执行编组之前或执行unmarshal之后显式调用适配器逻辑。