我需要使用jaxb生成xml,如下所示:
<item>
<key1 id="default">value1</key1>
<key2 id="default">value2</key2>
<key3 id="default">value3</key3>
</item>
如何在jaxb中使用@XmlPath执行此操作?
我用过下面的一个。但我有50左右的多个键如何实现这个?
@XmlPath("key1/@id")
private String attrValue = "default";
答案 0 :(得分:0)
@XmlPath
是EclipseLink MOXy JAXB (JSR-222)实施的扩展。您需要使用MOXy映射文件中的等效文件来获得所需的行为。
<强> oxm.xml 强>
您正在寻找的是为字段/属性应用多个可写映射的能力。目前无法通过注释完成此操作,但可以使用MOXy的外部映射文档完成。
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum12704491">
<java-types>
<java-type name="Item">
<java-attributes>
<xml-element java-attribute="attrValue" xml-path="key1/@id"/>
<xml-element java-attribute="attrValue" xml-path="key2/@id" write-only="true"/>
<xml-element java-attribute="attrValue" xml-path="key3/@id" write-only="true"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
<强>物品强>
package forum12704491;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
private String attrValue;
private String key1;
private String key2;
private String key3;
}
<强> jaxb.properties 强>
为了将MOXy指定为您的JAXB提供程序,您需要在与域模型相同的包中添加名为jaxb.properties
的文件,并带有以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
<强>演示强>
下面的演示代码演示了如何使用MOXy的外部映射文档进行引导。
package forum12704491;
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum12704491/oxm.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Item.class}, properties);
File xml = new File("src/forum12704491/input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Item item = (Item) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(item, System.out);
}
}
<强> input.xml中/输出强>
<?xml version="1.0" encoding="UTF-8"?>
<item>
<key1 id="default">value1</key1>
<key2 id="default">value2</key2>
<key3 id="default">value3</key3>
</item>