Generate tags with constants using XStream in Java

1

Hello I need to generate an xml with uppercase tags that would have to be final attributes in the template class to generate xml.

To do this, I'm trying to use the Java XStream API.

But being these final tags I can not generate a builder or create your sets because they are private?

Is there any way I can solve with XStream same or would it be better for another Java API to solve the problem?

Here is the class template I would need. If I leave the endless attributes, would it be strange to require that my xml tags need to be uppercase?

public class Metadados {
  private final String NOME_USUARIO;
  private final String IDADE_USUARIO;
  private final String NUMERO_PROTOCOLO;
}

My XML would need to look like this:

<NOME_USUARIO>Paulo</NOME_USUARIO>
<COD_USUARIO>36</COD_USUARIO>
<COD_PROTOCOLO>20170111092247</COD_PROTOCOLO>
    
asked by anonymous 25.07.2018 / 15:21

1 answer

0

An option for not having to declare your attributes in capital letters and with modifying of final access, would be the use of the annotation @XStreamAlias("nome do atributo") .

Example:

@XStreamAlias("NOME_USUARIO")
private String nomeUsuario;

See more at documentation .

If the attribute must necessarily be final , it does not make sense to have setter because the "end" access modifier indicates that the value of its attribute can not be changed after initialization.

@XStreamAlias("metadados")
public class Metadados {

    private final String NOME_USUARIO;
    private final String IDADE_USUARIO;
    private final String NUMERO_PROTOCOLO;

    public Metadados(String NOME_USUARIO, String IDADE_USUARIO, String NUMERO_PROTOCOLO) {
        this.NOME_USUARIO = NOME_USUARIO;
        this.IDADE_USUARIO = IDADE_USUARIO;
        this.NUMERO_PROTOCOLO = NUMERO_PROTOCOLO;
    }

    public String getNOME_USUARIO() {
        return NOME_USUARIO;
    }

    public String getIDADE_USUARIO() {
        return IDADE_USUARIO;
    }

    public String getNUMERO_PROTOCOLO() {
        return NUMERO_PROTOCOLO;
    }
}

Generating xml with XStream:

XStream xstream = new XStream(new DomDriver("UTF8", new NoNameCoder()));
xstream.processAnnotations(Metadados.class);
String xml = xstream.toXML(new Metadados("nome", "20", "123456"));
System.out.println(xml);

Result:

<metadados>
    <NOME_USUARIO>nome</NOME_USUARIO>
    <IDADE_USUARIO>20</IDADE_USUARIO>
    <NUMERO_PROTOCOLO>123456</NUMERO_PROTOCOLO>
</metadados>
    
25.07.2018 / 17:15