I have an XML file like below, and I want to convert it into a Java object.
<P1>
<CTS>
Hello
</CTS>
<CTS>
World
</CTS>
<P1>
So I created the following Java classes with their properties.
P1 class
@XmlRootElement
public class P1 {
@XmlElement(name = "CTS")
List<CTS> cts;
}
CTS class
public class CTS {
String ct;
}
Test Class
File file = new File("D:\\ContentTemp.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(P1.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
P1 p = (P1) jaxbUnmarshaller.unmarshal(file);
But I am getting the following error:
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "cts"
By default a JAXB (JSR-222) implementation creates mappings based on properties and annotated fields. When you annotate a field for which there is also a property it will cause this error.
You have two options:
Use
@XmlAccessorType(XmlAccessType.FIELD)You could annotate the field you need to specify
@XmlAccessorType(XmlAccessType.FIELD)on the class.Option #2 – Annotate the Property (get method)**
Alternatively you could annotate the
getmethod.For More Information
FULL EXAMPLE
CTS
You can use the
@XmlValueannotation to map to Java class to a complex type with simple content.P1
Demo
input.xml/Output
For More Information