0

Given an object as such :

@XmlRootElement(name = "node")
public class Node {
    @XmlElement(name = "data")
    private String data;
}

I want to get it serialized this way :

<node><data [string]/></node>

How can I do this ?

My string contains multiple attributes like x='1' y='2'.

servabat
  • 376
  • 4
  • 15
  • 1
    You are talking about `XML` attributes. See: https://stackoverflow.com/questions/5514752/xml-element-with-attribute-and-content-using-jaxb You are not allowed to put a `String` just like that inside node. You need to parse `data` and create `POJO` with annotated properties. – Michał Ziober Feb 14 '19 at 13:41

1 Answers1

0

You need to model your Java field data not as String, but as a class of its own (let's call it Data).

So, instead of

@XmlElement(name = "data")
private String data;

you need

@XmlElement(name = "data")
private Data data;

The new Data class then holds Java fields x and y

public class Data {
    @XmlAttribute(name = "x")
    private int x;

    @XmlAttribute(name = "y")
    private int y;
}

Note that x and y need to be annotated by @XmlAttribute instead of @XmlElement.

This will produce XML like for example

<node><data x="1" y="2"/></node>
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49