Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB how to create repeating elements with different attribute values

Tags:

java

xml

jaxb

xsd

I am trying to output the following XML using JAXB:

<ScreenData step="1" description="My descriotion">
    <element name="name1" type="type1" value="value1"/>
    <element name="name2" type="type2" value="value2"/>
</ScreenData>

To do this I'm using the following code:

screenData.getElement().add(element);
        element.setName("name1");
        element.setType("type1");
        element.setValueAttribute("value1");

        screenData.getElement().add(element);
        element.setName("name2");
        element.setType("type2");
        element.setValueAttribute("value2");

This is then what is output:

<ScreenData step="1" description="My First XML">
                <element name="name2" type="type2" value="value2"/>
                <element name="name2" type="type2" value="value2"/>
            </ScreenData>
like image 871
Colin747 Avatar asked May 29 '26 13:05

Colin747


1 Answers

You need to ensure that you are creating separate instances of Element. Currently you appear to be adding the same instance twice.

    Element element1 = new Element();
    screenData.getElement().add(element1);
    element1.setName("name1");
    element1.setType("type1");
    element1.setValueAttribute("value1");

    Element element2 = new Element();
    screenData.getElement().add(element2);
    element2.setName("name2");
    element2.setType("type2");
    element2.setValueAttribute("value2");

For More Information

  • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
like image 131
bdoughan Avatar answered May 31 '26 04:05

bdoughan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!