Dynamic XML and JAXB Tags

How can I use JAXB to serialize and deserialize the following XML, given that complement1 , 2 and 3 tags are not required, and XML can have complement4 , 5 , n ?

I was thinking about using the @XmlAnyElement annotation, but I need to know that the value "First" refers to the first addition, "Second" to the second, etc.

 <resource> <id>Identifier</id> <name>Name</name> <complement1>First</complement1> <complement2>Second</complement2> <complement3>Third</complement3> </resource> 
+4
source share
1 answer

I believe that you can use @XmlAnyElement and you have access to the element name.
You need to use the List Any construct.
When JAXB disables XML, you will have a list of DOM Element objects, each of which contains the name and content of the element.
I think you will have to manually enter into correspondence that each element tag name corresponds to the "complementN" pattern.

eg. this is a change from one of the Oracle samples:

Scheme:

 <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:sequence> <xs:any minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:sequence> </xs:complexType> </xs:element> 

Snippet from xjc generated class Person:

 ... @XmlRootElement(name = "person") public class Person { @XmlElement(required = true) protected String firstname; @XmlElement(required = true) protected String lastname; @XmlAnyElement(lax = true) protected List<Object> any; ... 

Check XML File:

 <?xml version="1.0" encoding="utf-8"?> <person> <firstname>David</firstname> <lastname>Francis</lastname> <anyItem1>anyItem1Value</anyItem1> <anyItem2>anyItem2Value</anyItem2> </person> 

Testing Class:

 JAXBContext jc = JAXBContext.newInstance( "generated" ); Unmarshaller u = jc.createUnmarshaller(); Person contents = (Person) u.unmarshal(Testit.class.getResource("./anysample_test1.xml")); System.out.println("contents: " + contents); System.out.println(" firstname: " + contents.getFirstname()); System.out.println(" lastname: " + contents.getLastname()); System.out.println(" any: "); for (Object anyItem : contents.getAny()) { System.out.println(" any item: " + anyItem); Element ele = (Element) anyItem; System.out.println(" ele name: " + ele.getTagName()); System.out.println(" ele text content: " + ele.getTextContent()); } 

Conclusion:

 contents: generated.Person@1bfc93a firstname: David lastname: Francis any: any item: [anyItem1: null] ele name: anyItem1 ele text content: anyItem1Value any item: [anyItem2: null] ele name: anyItem2 ele text content: anyItem2Value 
+5
source

Source: https://habr.com/ru/post/1412992/


All Articles