Pbm marshaling XML with classes generated via JAXB2

71 Views Asked by At

today is one day I think I'll become crazy.

I would like to generate some code to be able to mashshall/unmarshall XML files. I'm starting with an XSD that I pass to JAXB2 to generate Java classes via a maven module => It's OK.

Then I'm using those generated classes to make a first test to create a basic XML file but I've got the following error : Impossible to serialize type "com.xxx.xxx.AudioService" as an element because it is missing an @XmlRootElement annotation

public static void marshal() throws JAXBException, IOException {
        AudioService audioService = new AudioService();
        
        audioService.setName("TTS1");
        audioService.setEngineClass("Toto");
        
        JAXBContext context = JAXBContext.newInstance(AudioService.class);
        Marshaller mar= context.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        mar.marshal(audioService, new File("./test.xml"));
    }

But my generated class AudioService looks to :

package com.xxx.xxx;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlMixed;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.XmlValue;


@XmlRootElement(name = "audio-service")
public class AudioService {

    @XmlElement(name = "property")
    protected List<AudioService.Property> properties;
    @XmlElement(required = true)
    protected AudioService.Tts tts;

Does anybody have an idea why this error is thrown as everything seems ok ?

Note it's runing under java 17, javax.xml.bind:jaxb-api = 2.3.1 jakarta.xml.bind:jakarta.xml.bind-api=4.0.0

Thanks

1

There are 1 best solutions below

0
Pichou Bichou On

Thanks for your answers, It gives me the idea to check my dependencies. Finally I've found the pbm in the pom i had mixed dependencies with

<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>4.0.0</version>
</dependency> I had mix import with : 

And

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

Since I've removed javax.xml.bind packages It's now resolved !

Thanks again