I have a XML like this . And i want to convert it into JAVA object.
Hello
World
So I created following java classes with their properties.
P1 class
@XmlRootElement
public class P1 {
@XmlElement(name = "CTS")
List 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 following error -
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "cts"
解决方案
UPDATE
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.
Option #1 - Use @XmlAccessorType(XmlAccessType.FIELD)
You could annotate the field you need to specify @XmlAccessorType(XmlAccessType.FIELD) on the class.
@XmlRootElement(name="P1)
@XmlAccessorType(XmlAccessType.FIELD)
public class P1 {
@XmlElement(name = "CTS")
List cts;
}
Option #2 - Annotate the Property (get method)
Alternatively you could annotate the get method.
@XmlRootElement(name="P1)
public class P1 {
List cts;
@XmlElement(name = "CTS")
public List getCts() {
return cts;
}
}
For More Information
FULL EXAMPLE
CTS
You can use the @XmlValue annotation to map to Java class to a complex type with simple content.
@XmlAccessorType(XmlAccessType.FIELD)
public class CTS {
@XmlValue
String ct;
}
P1
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="P1")
@XmlAccessorType(XmlAccessType.FIELD)
public class P1 {
@XmlElement(name = "CTS")
List cts;
}
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(P1.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum13987708/input.xml");
P1 p1 = (P1) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(p1, System.out);
}
}
input.xml/Output
Hello
World
For More Information