1

I have classes defined as:

@XmlRootElement( name = "RootNode" )
public class RootNode{
.....
    @XmlElement( name = "code", required = true )
    protected CodeWord code;

    @XmlElement( name = "text" )
    protected EncText text;
.....
}

While class EncText looks like:

@XmlType( name = "EncText ",
        propOrder = {
                "language"
        } )
public class EncText {
.....
    @XmlElement( name = "language" )
    protected LANG language;

    @XmlAttribute( name = "mediaType" )
    @XmlJavaTypeAdapter( CollapsedStringAdapter.class )
    protected String mediaType;
.....
}

In the EncText, I might have text data which need to be added as the text node. I would like to have output, after marshalling, like:

<RootNode>
    <text mediaType="plain/text">
        Data come from database.
    </text>
</RootNode>

How can I define property in, say EncText, as well proper setter and getter to allow me to do so? I tried to define a @XmlValue property in EncText. However, error showed that XmlElement can not coexist with XmlValue. I need advices for this. Thanks a lot.

Joey
  • 45
  • 5

1 Answers1

0

I tried to define a @XmlValue property in EncText.

That should have worked fine, but since you didn't show what you tried, here's how:

@XmlRootElement( name = "RootNode" )
class RootNode {
    @XmlElement( name = "text" )
    protected EncText text;
}
class EncText {
    @XmlAttribute( name = "mediaType" )
    protected String mediaType;

    @XmlValue
    protected String textValue;
}

Test

RootNode rootNode = new RootNode();
rootNode.text = new EncText();
rootNode.text.mediaType = "plain/text";
rootNode.text.textValue = "Data come from database.";

JAXBContext jaxbContext = JAXBContext.newInstance(RootNode.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rootNode, System.out);

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootNode>
    <text mediaType="plain/text">Data come from database.</text>
</RootNode>
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • But the question is that, in the original codes, there might be some @XmlElement definitions in the EncText class. Therefore, when marshalling, errors came up saying xmlelement cannot mixed with xmlvalue. – Joey Feb 14 '20 at 14:33
  • @Joey How did you expect an element with both `@Value` and `@Element` to be rendered in XML? First define your goal, so please show what XML you desire to generate. – Andreas Feb 14 '20 at 23:12
  • @Joey If you truly intend for the content of the element to contain both plain text and sub-elements, then that is referred to as **mixed** content. See e.g. [How to deal with JAXB ComplexType with MixedContent data?](https://stackoverflow.com/q/12568247/5221149) – Andreas Feb 14 '20 at 23:15
  • The hyperlinked post is pretty much the one I am looking for. Thanks a lot. – Joey Feb 15 '20 at 09:45