Reputation: 128041
Recently I have faced a problem which seems to be very common: how to represent an XML element with attributes and simple textual content, like this:
<elem attr="aval">elemval</elem>
using JAXB.
I've found many advices on how to do this, but every one of these advices involves manual editing of binding classes.
I have a set of schemas and I use XJC to convert these schemas to Java classes. However, it seems that it produces wrong code, i.e. it does not generate methods to set plain content, there are methods for setting attributes only.
Is it possible to fix this behavior of XJC? Extensive googling didn't help on this question.
Upvotes: 3
Views: 3275
Reputation: 149047
Below is an XML schema that defines the XML structure for you use case.
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/schema"
xmlns:tns="http://www.example.org/schema" elementFormDefault="qualified">
<element name="elem">
<complexType>
<simpleContent>
<extension base="string">
<attribute name="attr" type="string" />
</extension>
</simpleContent>
</complexType>
</element>
</schema>
Generating a JAXB model from this XML schema will result in the following class:
package forum12859885;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "elem")
public class Elem {
@XmlValue
protected String value;
@XmlAttribute(name = "attr")
protected String attr;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getAttr() {
return attr;
}
public void setAttr(String value) {
this.attr = value;
}
}
Upvotes: 6