Home Dynamically adding attributes without changing the java object
Reply: 1

Dynamically adding attributes without changing the java object

raccoon
1#
raccoon Published in 2017-12-07 22:05:24Z

I want to add another new attributes the an field without changing the java object.

<field  attribute1 = "1"  attribute2 = "2"  attribute3 = "3"> value</filed>

@XmlRootElement(name = "field ")
public class Field 
{
    @XmlAttribute(name="attribute1")
    private String attribute1;

    @XmlAttribute(name="attribute2")
    private String attribute2;

    @XmlAttribute(name="attribute3")
    private String attribute3;
}

If I want to add a new attribute 4 to the XMLwithout changing the Field class(adding new field to the class and recompile).

Is there a way to do that?

Andreas
2#
Andreas Reply to 2017-12-07 22:29:01Z

If your want the Java class to be able to store any attribute, you need a Map to store the attribute name/value pairs, and you need to annotate that field with @XmlAnyAttribute.

Here is example code:

@XmlRootElement(name = "field")
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
    @XmlAttribute(name="attribute1")
    String attribute1;

    @XmlAttribute(name="attribute2")
    String attribute2;

    @XmlAttribute(name="attribute3")
    String attribute3;

    @XmlAnyAttribute
    Map<String, String> attributes;
}

Test

String xml = "<field attribute1=\"A\"" +
                   " attribute2=\"B\"" +
                   " attribute3=\"C\"" +
                   " attribute4=\"D\"" +
                   " foo=\"Bar\" />";
JAXBContext jaxbContext = JAXBContext.newInstance(Field.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Field field = (Field) unmarshaller.unmarshal(new StringReader(xml));
System.out.println("field.attribute1 = " + field.attribute1);
System.out.println("field.attribute2 = " + field.attribute2);
System.out.println("field.attribute3 = " + field.attribute3);
System.out.println("field.attributes = " + field.attributes);

Output

field.attribute1 = A
field.attribute2 = B
field.attribute3 = C
field.attributes = {attribute4=D, foo=Bar}

As you can see, the two "extra" attributes were added to the map.

If you run the same test but without any attributes, i.e. with xml = "<field/>";, you get:

field.attribute1 = null
field.attribute2 = null
field.attribute3 = null
field.attributes = null

The attributes field is left unassigned, i.e. null. It is not an empty map.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.318196 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO