Reputation: 41
Hi I am unmarshalling a XML file that has a tag that can contain both a value or a list of elements. I was wondering what the best approach is for unmarshalling this kind of XML. Example:
<attributes>
<attribute>value1</attribute>
<attribute>value2</attribute>
<attribute>value3</attribute>
<attribute>value4</attribute>
<attribute>
<value>value11</value>
<value>value12</value>
<value>value13</value>
<value>value14</value>
<value>value15</value>
</attribute>
<attribute>value5</attribute>
<attribute>value6</attribute>
</attributes>
I can't change the way of how the XML is build up so I am hoping someone has a answer. Thank you.
Upvotes: 2
Views: 605
Reputation: 26961
Basic steps to read-write xml using JaxB
/ Unmarshaller
and XSD
Create a valid XSD
file of your XML
structure. Find here an online generator.
Will be something like this (but maybe you need to modify manually some detail, in your XML structure seems you can create the Attribute
class wrapping several <attribute>
but I dont know for sure if you can have more than one <attributes>
tag):
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="attributes">
<xs:complexType>
<xs:sequence>
<xs:element name="attribute" maxOccurs="unbounded" minOccurs="0">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element type="xs:string" name="value" maxOccurs="unbounded" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Place it in your project folder.
XSD
file and auto-generate JAXB classes.Use Unmarshaller
to populate auto-generated classes from XML file:
Unmarshaller u = jc.createUnmarshaller();
Attributes attributes = (Attributes) u.unmarshal( new FileInputStream( "yourFile.xml" ) );
That's it... JaxB will take care of classes, attributes, populate, write/read xml...
Upvotes: 2