Jaxb Xpath: ¿Cómo usar varios XPath a un mismo frijol Java?
-
13-12-2019 - |
Pregunta
Necesito generar XML usando JAXB de la siguiente manera:
<item>
<key1 id="default">value1</key1>
<key2 id="default">value2</key2>
<key3 id="default">value3</key3>
</item>
¿Cómo hacer esto usando @xmlpath en Jaxb?
He utilizado por debajo de uno.Pero tengo múltiples claves alrededor de 50. ¿Cómo lograr esto?
@XmlPath("key1/@id")
private String attrValue = "default";
Solución
@XmlPath
es una extensión en la eclipselink moxy implementación de jaxb (JSR-222) . Tendrá que usar el equivalente en el archivo de asignación de Moxy para obtener el comportamiento deseado.
oxm.xml
Lo que está buscando es la capacidad de aplicar mapas de múltiples escrituras para un campo / propiedad. Esto se puede hacer actualmente a través de anotaciones, pero se puede hacer utilizando el documento de mapeo externo de 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>
item
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
Para especificar moxy como su proveedor de Jaxb, debe agregar un archivo llamado jaxb.properties
en el mismo paquete que su modelo de dominio con la siguiente entrada (consulte: http://blog.bdoughan.com/2011/05/specify-clipselink-moxy-as-your.html )
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
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);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<item>
<key1 id="default">value1</key1>
<key2 id="default">value2</key2>
<key3 id="default">value3</key3>
</item>