JAXB Marshalling: Creating an empty element with an attribute - jaxb

I use a JAXB marshaller and I would like to add an empty element with a specific attribute. This is a dummy class:
#XmlRootElement(name="observation")
public class Observation {
#XmlAttribute
public static final String classCode = "OBS";
#XmlAttribute
public static final String moodCode = "EVN";
private String data;
#XmlElement
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
This creates the following XML:
<observation classCode="OBS" moodCode="EVN">
<data>fsdfsdfd</data>
</observation>
Is there any way to add a new element with a specific attribute only (no value at all)? E.g.
<observation classCode="OBS" moodCode="EVN">
<templateId root="2.16.840.1.113883.10.20.1.31"/>
<data>fsdfsdfd</data>
</observation>

This should do it:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "TemplateIdType")
public class TemplateIdType {
#XmlAttribute(name = "root")
protected String root;
// getter and setter
}
(And you add an element of this class to Observation.)

Related

Why is XStream ignoring #XmlTransient?

Does XStream handle JAXB #XmlTransient attributes by default? XStream seems to be ignoring the #XmlTransient attribute & serializing the field anyway.
In the sample code below. ExampleClass2 is getting serialized even though I don't want it to be. Further details are that these classes are being populated by OpenJPA.
XStream Code
XStream _x0 =null;
_x = XStreamImpl.getInstance();
_x.toXML(_object)
Class I want to serialize
#DataCache
#Entity
public class ExampleClass implements Serializable {
private short defaultOption;
private int primaryKey;
private short orderId;
#XmlTransient
private ExampleClass2 _exampleClass2;
#XmlTransient
public ExampleClass2 getTblPpwsCommCfgCombo() {
return _exampleClass2;
}
#XmlTransient
public void setExampleClass2(ExampleClass2 _exampleClass2) {
this._exampleClass2 = _exampleClass2;
}
public short getDefaultOption() {
return defaultOption;
}
public void setDefaultOption(short defaultOption) {
this.defaultOption = defaultOption;
}
public short getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(int primaryKey) {
this.primaryKey = primaryKey;
}
public short getOrderId() {
return orderId;
}
public void setOrderId(short orderId) {
this.orderId = orderId;
}
}
You can use the #Transient annotation or transiet key word:
#Transient
private ExampleClass2 _exampleClass2;
~

JAXB define java class for a xml file with attributes in nested elements

I want to define a java class and then use JAXB to marshalling its instances to a xml file.
The output I want looks like:
<paths>
<path action="R" kind="file" copyfrom-path="file1" copyto-path="file2">file2</path>
<path action="M" kind="file">file3</path>
</paths>
I defined a java class as follows:
#XmlRootElement(name = "paths")
#XmlAccessorType(FIELD)
public class changed_paths
{
private List<String> path;
public changed_paths()
{
path = new ArrayList<String>();
}
public List<String> getPath()
{
return path;
}
public void setPath(List<String> path)
{
this.path = path;
}
public void addPath(String p)
{
path.add(p);
}
}
Using the above java class, I can generate output xml file without the attributes of <path></path> elements. Like below:
<paths>
<path>file2</path>
<path>file3</path>
</paths>
I tried to define the attributes in changed_paths class like below :
#XmlAttribute
private String kind;
public void setKind(String kind){
this.kind = kind;
}
public String getKind(){
return this.kind;
}
But this will output a xml file with attributes "kind" in tag <paths></paths> but not in its nested <path></path> tags.
The other problem is that when the attribute name contains "-" (e.g. copyfrom-path), java won't allow me to define such variables with "-" in its name.
Can someone please tell me how to define:
1. attributes in <path></path>?
2. attributes with "-" in their names?
Can someone please give me some help?
Thank you very much!
I find the answers. To create attributes for <path></path>, I defined class path for this tag. And defined another class paths for <paths></paths> .
To create attributes with "-" in their names, I use annotation #XmlAttribute(name = "copyfrom-path")
#XmlAccessorType(FIELD)
public class path
{
#XmlAttribute
private String kind;
#XmlAttribute
private String action;
#XmlAttribute(name = "copyfrom-path")
private String copyfrom;
#XmlAttribute(name = "copyfrom-rev")
private String copyto;
#XmlValue
private String value;
public void setKind(String kind)
{
this.kind = kind;
}
public String getKind()
{
return this.kind;
}
public void setAction(String action)
{
this.action = action;
}
public String getAction()
{
return this.action;
}
public void setValue(String value)
{
this.value = value;
}
public String getValue()
{
return this.value;
}
public void setCopyfrom(String p)
{
this.copyfrom = p;
}
public String getCopyfrom()
{
return this.copyfrom;
}
public void setCopyto(String p)
{
this.copyto = p;
}
public String getCopyto()
{
return this.copyto;
}
}
#XmlRootElement(name = "paths")
#XmlAccessorType(FIELD)
public class paths
{
private List<path> paths;
public paths()
{
paths = new ArrayList<path>();
}
public List<path> getPaths()
{
return paths;
}
public void setPaths(List<path> paths)
{
this.paths = paths;
}
public void addPath(path p)
{
paths.add(p);
}
}

#XmlPath(".") conflicts with #XmlAdapter

having this Jaxb Xml definition, i try to remove the Map Elements Wrapper by adding #XmlPath(".") but it cause exception during the unmarchaling
#XmlRootElement
public abstract class ViewElement{
#XmlJavaTypeAdapter(value=EventAdapter.class)
public Map<Event, String> getEvents() {
}
private transient Class entityType;
public Class getEntityType() {
return entityType;
}
}
And the EventAdapter is
public class EventAdapter extends XmlAdapter<EventAdapter.AdaptedMap, Map<Event, String>> {
public static class AdaptedMap {
#XmlVariableNode("key")
List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();
}
public static class AdaptedEntry {
#XmlTransient
public String key;
#XmlValue
public String value;
}
.....
}
my output was
<element>
<events>
<onCellEdit>do some thing<onCellEdit>
</events>
<entityType>com.agitech.erp.model.erp.ErpFolder</entityType>
<element>
I try to remove the <events> tag by adding #XmlPath(".")
#XmlPath(".")
#XmlJavaTypeAdapter(value=EventAdapter.class)
public Map<Event, String> getEvents() {
}
The output is good
<element>
<onCellEdit>do some thing<onCellEdit>
<entityType>com.agitech.erp.model.erp.ErpFolder</entityType>
<element>
but the unmarchaling faileds
Caused by: Exception [EclipseLink-3002] (Eclipse Persistence Services - 2.6.0.v20140809-296a69f): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [], of class [class java.lang.String], from mapping [org.eclipse.persistence.oxm.mappings.XMLDirectMapping[entityType-->view.entityType/text()]] with descriptor [XMLDescriptor(com.agitech.erp.view.BeanView --> [DatabaseTable(view), DatabaseTable(viewFrame), DatabaseTable(viewElement)])], could not be converted to [class java.lang.Class].
Internal Exception: java.lang.ClassNotFoundException:
at org.eclipse.persistence.exceptions.ConversionException.couldNotBeConvertedToClass(ConversionException.java:95)
at org.eclipse.persistence.internal.helper.ConversionManager.convertObjectToClass(ConversionManager.java:446)
Debuging Jaxb bring me to the line
org.eclipse.persistence.internal.oxm.XMLDirectMappingNodeValue
public void endElement(XPathFragment xPathFragment, UnmarshalRecord unmarshalRecord) {
...
line 205 unmarshalRecord.setAttributeValue(convertedValue, xmlDirectMapping);
}
During the unmarchaling of entityType value, the UnmarshalRecordImpl.currentObj contains the EventAdapter instead of the parent element
I modify org.eclipse.persistence.internal.oxm.record.UnmarshalRecordImpl
public XPathNode getNonAttributeXPathNode(String namespaceURI, String localName, String qName, Attributes attributes) {
....
if(null == resultNode && null == nonPredicateNode) {
// ANY MAPPING
resultNode = xPathNode.getAnyNode();
// by default it return the EventAdapter, changing it to NULL fix my problem
}
....
}
Not a safe solution
I have been able to reproduce the issue that you are seeing, but haven't yet worked out the cause. You can use the following bug to track the progress on this issue:
http://bugs.eclipse.org/457169
After trying a lot of things, I was able to find a workaround for this issue. I thought of posting here the same so it can be helpful to someone else in the future. The lead has confirmed the issue around 5 years ago but seems like they have not fixed it and I was facing a similar issue.
Basically, we can use the beforeMarshal and afterUnmarshal methods to change the values in the fields.
You need to create a field List<Object> with #XmlAnyElement(lax=true) along with Map<String,Object>.
Remove the #XmlPath(".") and the XMLAdapter class.
Mark the field Map<String, Object> with #XmlTransient.
Now within the beforeMarshal and afterMarshal fields, you can exchange the data. During the unmarshal in beforeunmarshal, all the unknown field values will be present within the List<Object> loop over it and add it to the Map<String, Object>.
Similarly during the marshaling, you can move the values Map<String, Object> to List<Object> by creating the DOM elements.
Marshaling all values are added to root as DOM Elements are present and during Unmarshaling known values are read first and then-unknown values are stored within List<Object> due to #XmlAnyElement.
I have created an example using the Customer class, you can modify it accordingly for your need.
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, visible = true, property = "isA")
#JsonInclude(Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
#XmlRootElement(name = "Customer")
#XmlType(name = "Customer", propOrder = {"name", "age", "otherElements"})
#XmlAccessorType(XmlAccessType.FIELD)
#Getter
#Setter
#AllArgsConstructor
#ToString
#NoArgsConstructor
public class Customer {
#XmlTransient
private String isA;
private String name;
private String age;
#XmlAnyElement(lax = true)
#JsonIgnore
private List<Object> otherElements = new ArrayList<>();
#JsonIgnore
#XmlTransient
private Map<String, Object> userExtensions = new HashMap<>();
#JsonAnyGetter
#JsonSerialize(using = CustomExtensionsSerializer.class)
public Map<String, Object> getUserExtensions() {
return userExtensions;
}
#JsonAnySetter
public void setUserExtensions(String key, Object value) {
userExtensions.put(key, value);
}
private void beforeMarshal(Marshaller m) throws ParserConfigurationException {
System.out.println("Before Marshalling User Extension: " + userExtensions);
ExtensionsModifier extensionsModifier = new ExtensionsModifier();
otherElements = extensionsModifier.Marshalling(userExtensions);
System.out.println("Before Marshalling Final Other Elements " + otherElements);
userExtensions = new HashMap<>();
}
private void afterUnmarshal(Unmarshaller m, Object parent) throws ParserConfigurationException {
System.out.println("After Unmarshalling : " + otherElements);
ExtensionsModifier extensionsModifier = new ExtensionsModifier();
userExtensions = extensionsModifier.Unmarshalling(otherElements);
otherElements = new ArrayList();
}
}
You can refer the creation of DOM ELEMENTS here:https://stackoverflow.com/a/24239105/7584240
You can refer my complete answer here: https://stackoverflow.com/a/67923216/7584240

Jaxb #XmlAttribute in #XmlElement

Please, as it could indicate the 'type' attribute on elements 'horaIniJornada' and 'tiempoJornadamedia'?
#XmlElement(name = "tiempoJornadaMedia")
public String getTimeJournalMedia() {
return timeJournalMedia;
}
#XmlAttribute(name = "tipo")
public String getTypeHourInitJournal() {
return typeHourInitJournal;
}
<configuraciones>
<almacen>MD</almacen>
<cliente>MKD</cliente>
<secciones>
<seccion>
<seccId>70</seccId>
<horaIniJornada tipo="T">23:00:00</horaIniJornada>
<tiempoJornadaMedia tipo="T">07:30:00</tiempoJornadaMedia>
</seccion>
<seccion>
<seccId>71</seccId>
<horaIniJornada tipo="T">23:00:00</horaIniJornada>
<tiempoJornadaMedia tipo="T">07:30:00</tiempoJornadaMedia>
</seccion>
</secciones>
</configuraciones>
You'll need a separate class for that. Something like TimeHournalMedia with an #XmlAttribute and #XmlValue property. Something like:
#XmlValue
public String getValue() {
return value;
}
#XmlAttribute(name = "tipo")
public String getTypeHourInitJournal() {
return typeHourInitJournal;
}
Then you'll have in your main class:
#XmlElement(name = "tiempoJornadaMedia")
public TimeHournalMedia getTimeJournalMedia() {
return timeJournalMedia;
}
To get the textual content you'll do getTimeJournalMedia().getValue(), to get the attribute - getTimeJournalMedia().getgetTypeHourInitJournal(), something like that.
There are further options with MOXy #XmlPath.

How to override JAXB #XMLAccessorType(XMLAccessType.FIELD) specified at a Class level with #XMLElement on a getter method for a property?

In the example code below, Employee class has been specified with JAXB field level access type. For the property dept, however, the access type has been specified at getter method level with #XMLElement annotation.
During marshalling of Organization class, the following exception is thrown -
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "dept"
this problem is related to the following location:
at public java.lang.String com.playground.jaxb.Employee.getDept()
this problem is related to the following location:
at private java.lang.String com.playground.jaxb.Employee.dept
Can you help me understand why this overriding of JAXB accessor type is not working please? Also any solution would be highly appreciated.
Example
Root Element Class
package com.playground.jaxb;
#XMLRootElement(name="organization")
public class Organization {
#XmlElementWrapper(name = "employees")
#XmlElement(name = "employee")
private Set<Employee> employees;
public Organization{}
// Remainder omitted...
}
Employee Class
package com.playground.jaxb;
#XMLAccessorType(XMLAccessType.FIELD)
public class Employee {
private String name;
private String dept;
#XMLElement(name="department")
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public Employee {}
// Remainder omitted...
}
You can re-name getter/setter pair, e.g. getDept() -> getDepartment()
private String dept;
#XmlElement(name="department")
public String getDeptartment() {
return dept;
}
public void setDeptartment(String dept) {
this.dept = dept;
}
but in this case you will have duplicate in XML
<dept>my_dept</dept>
<department>my_dept</department>
Or you can annotate field dept with #XmlTransient annotation, if you want to change access type it.
#XmlTransient
private String dept;
#XmlElement(name="department")
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
In this case, dept field will be ignored and getter/setter pair will be used instead

Resources