Pergunta

Preciso gerar xml usando jaxb conforme abaixo:

<item>
    <key1 id="default">value1</key1>
    <key2 id="default">value2</key2>
    <key3 id="default">value3</key3>
</item>

como fazer isso usando @XmlPath no jaxb?

eu usei abaixo de um.Mas eu tenho várias chaves em torno de 50.como conseguir isso?

   @XmlPath("key1/@id")
    private String attrValue = "default";
Foi útil?

Solução

@XmlPath é uma extensão do EclipseLink MOXy implementação de JAXB (JSR-222).Você precisará usar o equivalente no arquivo de mapeamento do MOXy para obter o comportamento desejado.

oxm.xml

O que você está procurando é a capacidade de aplicar vários mapeamentos graváveis ​​para um campo/propriedade.Atualmente, isso não pode ser feito por meio de anotações, mas pode ser feito usando o documento de mapeamento externo do 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 seu provedor JAXB, você precisa adicionar um arquivo chamado jaxb.properties no mesmo pacote do seu modelo de domínio com a seguinte entrada (consulte: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demonstração

O código de demonstração abaixo demonstra como inicializar usando o documento de mapeamento externo do 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/Saída

<?xml version="1.0" encoding="UTF-8"?>
<item>
   <key1 id="default">value1</key1>
   <key2 id="default">value2</key2>
   <key3 id="default">value3</key3>
</item>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top