O
O
Oleg2021-01-22 15:03:42
Java
Oleg, 2021-01-22 15:03:42

What is the correct way to specify attributes for tags in JAXB?

Greetings gentlemen!
At me a question on implementation a trace. tasks. Example from the textbook...
There is a code

@XmlType( propOrder = { "name", "capital", "foundation", "continent" , "population"} )
@XmlRootElement( name = "Country" )
public class Country
{
     
    @XmlElement (name = "Country_Population")
    public void setPopulation( int population )
    {
        this.population = population;
    }
 
 
    @XmlElement( name = "Country_Name" )
    public void setName( String name )
    {
        this.name = name;
    }
 
    @XmlElement( name = "Country_Capital" )
    public void setCapital( String capital )
    {
        this.capital = capital;
    }
    @XmlAttribute( name = "importance", required = true )
    public void setImportance( int importance )
    {
        this.importance = importance;
    }
...


Which after marshaling produces:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Country importance="1">
 <Country_Name>Spain</Country_Name>
 <Country_Capital>Madrid</Country_Capital>
 <Country_Foundation_Date></Country_Foundation_Date>
 <Country_Continent>Europe</Country_Continent>
 <Country_Population>45000000</Country_Population>
</Country>


And I need to get output like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Country importance="1">
 <Country_Name>Spain</Country_Name>
 <Country_Capital>Madrid</Country_Capital>
 <Country_Foundation_Date></Country_Foundation_Date>
 <Country_Continent name="Europe"/>
 <Country_Population value="45000000"/>
</Country>


Those. in some tags, values ​​must be specified in ATTRIBUTES.
Specifying multiple "@XmlAttribute" outputs them all in one tag (in this case, "Country").

This is what it turns out .... What do I need for each such case "",
Create a separate object (class) of the "Country_Continent" type?

Or is there still a more elegant and simple solution that is not visible to my eyes on the Internet?

Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ryabos, 2021-01-23
@VDT2

JAXB annotations indicate membership in the class in which they are declared. That is, if you specify @XmlAttribute, then the attribute will be added exactly to the class
. To use a more "fine" marshalling configuration, create a class for each tag, and store a reference to an object of this class in the main class field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question