我还有一个更棘手的问题:
E.g. Person Class has: --String firstName --String lastName --Map stringMap
Person person = new Person ();
person.setFirstName("FirstName");
person.setLastName("LastName");
Map<String,String> stringMap = new HashMap<String,String>();
stringMap.put("IwantThisKeyInXml","IwantThisValueInXml");
stringMap.put("IDONTwantThisKeyInXml","IDONTwantThisValueInXml");
InputStream iStream1 = classLoader.getResourceAsStream("person-binding.xml");
List<Object> fileList = new ArrayList<Object>();
fileList.add(iStream1);
Map<String, Object> properties = new HashMap<String,Object>();
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, fileList);
JAXBContext ctx = JAXBContext.newInstance(new Class[] { GaDictionary.class, Person.class }, properties);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Writer output = new StringWriter();
marshaller.marshal(person, output);
System.out.println(output);
person-binding.xml 如下
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="my.test.model" xml-mapping-metadata-complete="true">
<xml-schema
element-form-default="QUALIFIED"/>
<java-types>
<java-type name="Person" xml-accessor-type="NONE">
<xml-root-element/>
<xml-type prop-order="firstName lastName"/>
<java-attributes>
<xml-element java-attribute="firstName" name="first-name"/>
<xml-element java-attribute="lastName" name="last-name"/>
<xml-element java-attribute="stringMap" name="string-map"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
因此,结果的定义是:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<first-name>FirstName</first-name>
<last-name>LastName</last-name>
<string-map>
<entry>
<key>IwantThisKeyInXml</key>
<value>IwantThisKeyInXml</value>
</entry>
<entry>
<key>IDONTwantThisKeyInXml</key>
<value>IDONTwantThisKeyInXml</value>
</entry>
</string-map>
</person>
如何在 stringMap 上排除该条目?我尝试了虚拟访问方法,但也许我无法正确配置它?!我应该在编组后删除该值吗?这可能是一种智能且可维护的方式吗?
最后一个问题是我的属性是否为空值。如何配置 person-binding-xml 文件 (oxm.file) 以使相关 xml 标记为空?
我可以更改模型类,但如果可能的话,我宁愿不要添加任何代码行。(这就是我填充 xml 文件的原因)
所以我想得到的结果是:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<first-name>FirstName</first-name>
<last-name>LastName</last-name>
<string-map>
<entry>
<key>IwantThisKeyInXml</key>
<value>IwantThisKeyInXml</value>
</entry>
</string-map>
</person>
对于第二个相关问题:我尝试了 nillable="true" 但它不起作用!因此,例如,如果我有一个 stringMap 或 firstName 或其他东西的空值,我将分别获得并用任何主体关闭标签。
或者我想获得的另一种方式是:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<first-name>FirstName</first-name>
<last-name>LastName</last-name>
<string-map>
<entry>
<key>IwantThisKeyInXml</key>
<value>IwantThisKeyInXml</value>
</entry>
<entry><!-- I have the entry but I have an empty value-->
<key>KEY</key>
<value></value>
</entry>
</string-map>
</person>
谢谢大家