JaxB XPath: come utilizzare più XPath in uno stesso Java Bean?
-
13-12-2019 - |
Domanda
Devo generare XML usando JaxB come sotto:
<item>
<key1 id="default">value1</key1>
<key2 id="default">value2</key2>
<key3 id="default">value3</key3>
</item>
.
Come fare questo usando @xmlpath in Jaxb?
Ho usato sotto uno.Ma ho più tasti circa 50. Come achedire questo?
@XmlPath("key1/@id")
private String attrValue = "default";
. Soluzione
@XmlPath
è un'estensione in eclipselink moxy implementazione di jaxb (jsr-222) . Avrai bisogno di utilizzare l'equivalente nel file di mappatura di Moxy per ottenere il comportamento desiderato.
Quello che stai cercando è la possibilità di applicare più mappature scrivibili per un campo / proprietà. Questo non può attualmente essere fatto tramite annotazioni, ma può essere fatto usando il documento di mappatura esterno di 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>
.
Articolo
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
Per specificare Moxy come provider JAXB è necessario aggiungere un file chiamato jaxb.properties
nello stesso pacchetto del modello di dominio con la seguente voce (vedere: http://blog.bdoughan.com/2011/05/specify-eclipselink-moxy-as-your.html )
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
.
Il codice DEMO sotto dimostra come bootstrap utilizzando il documento di mappatura esterno di 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);
}
}
.
<?xml version="1.0" encoding="UTF-8"?>
<item>
<key1 id="default">value1</key1>
<key2 id="default">value2</key2>
<key3 id="default">value3</key3>
</item>
.