When I run this code:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
public class JavaToXMLDemo {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Employee object = new Employee();
object.setCode("CA");
object.setName("Cath");
object.setSalary(300);
m.marshal(object, System.out);
}
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Employee {
private String code;
private String name;
private int salary;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int population) {
this.salary = population;
}
}
I get
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<code>CA</code>
<name>Cath</name>
<salary>300</salary>
</employee>
Which is correct, so my question is why does it change the Employee to employee? Is it possible to make it print with uppercase E, instead of employee?
This is what I actually wanted to have:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
<code>CA</code>
<name>Cath</name>
<salary>300</salary>
</Employee>
Thanks!
To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations. Now get the Unmarshaller instance from JAXBContext . It's unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.
A JavaBean property, when annotated with @XmlElement annotation is mapped to a local element in the XML Schema complex type to which the containing class is mapped.
fragment – It determines whether or not document level events will be generated by the Marshaller. Value can be true or false .
The behaviour you are seeing is the result of the standard JAXB (JSR-222) XML name to Java name conversion algorithm.
You can use the @XmlRootElement
annotation to specify a name:
@XmlRootElement(name="Employee")
@XmlAccessorType(XmlAccessType.FIELD)
class Employee {
...
}
I'm the EclipseLink JAXB (MOXy) lead, and we have an extension that allows you to override the default name conversion algorithm that you may be interested in:
For specific elements...
@XmlElement( name = "Code")
private String code;
For the object....
@XmlRootElement(name="Employee")
public class Employee{ ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With