I have 2 classes, one extends the other. The superclass marshals correctly, but the subclass, which adds one attribute, does not. The extra attribute is not present in the XML.
Superclass:
#XmlRootElement()
#XmlAccessorType(XmlAccessType.NONE)
public class SessionRecord extends Record {
SimpleDateFormat hhmm = new SimpleDateFormat("HH:mm");
SimpleDateFormat day = new SimpleDateFormat("EEEEE");
#XmlAttribute protected int sessionId;
#XmlAttribute protected boolean open;
#XmlAttribute protected boolean night;
protected Date start;
protected Date finish;
protected boolean setup;
protected boolean takedown;
#XmlAttribute
public String getDescription() {
if (start==null) start = new Date();
if (finish==null) finish = new Date();
return day.format(start)+(night ? " Night " : " ")+hhmm.format(start)+"-"+hhmm.format(finish)+" "+type();
}
private String type() {
return setup ? "Setup" : (open ? "Open" : (takedown ? "Takedown" : ""));
}
#XmlAttribute
public boolean isSetupTakedown() {
return setup || takedown;
}
}
This produces XML elements similar to this:
<sessionRecord setupTakedown="true" description="Saturday 09:00-13:00 Setup" night="false" open="false" sessionId="0"/>
which is OK.
But the subclass:
#XmlRootElement()
public class VolunteerSession extends SessionRecord {
#XmlAttribute private boolean available;
}
Produces identical output, the available attribute is not marshalled. Why is JAXB not marshalling the extra attribute?
EDIT
further information:
Record superclass is merely this:
public abstract class Record {}
Here is the class representing the top-level document element. It contains lists of Records:
#XmlRootElement(name="response")
#XmlSeeAlso({
RecordList.class,
VolunteerAssignment.class,
VolunteerRecord.class,
SessionRecord.class,
VolunteerSession.class,
VolunteerArea.class,
PossibleAssignment.class})
public class XMLResponse {
#XmlAttribute private String errorMessage;
private List<RecordList<? extends Record>> recordLists = new ArrayList<RecordList<? extends Record>>();
//snip...
public void setError(String errorMessage) {
this.errorMessage = errorMessage;
}
#XmlMixed
public List<RecordList<? extends Record>> getRecordLists() {
return recordLists;
}
}
and finally, RecordList
#XmlRootElement()
public class RecordList<T extends Record> {
#XmlAttribute private String name;
#XmlAttribute private int total;
#XmlAttribute private int count;
#XmlAttribute private int start;
#XmlAttribute private boolean update;
private List<T> records;
// snip constructors, setters
#XmlMixed
public List<T> getRecords() {
return records;
}
}
It sounds as though the VolunteerSession class is not being included in the JAXBContext. This can happen depending on how you created your JAXBContext. Below is some example code where the same object is marshalled based on 3 different instances of JAXBContext each bootstrapped off a different class.
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
VolunteerSession volunteerSession = new VolunteerSession();
marshal(VolunteerSession.class, volunteerSession);
marshal(SessionRecord.class, volunteerSession);
marshal(XMLResponse.class, volunteerSession);
}
private static void marshal(Class bootstrapClass, Object object) throws Exception {
System.out.println(bootstrapClass.getName());
JAXBContext jc = JAXBContext.newInstance(bootstrapClass);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, System.out);
System.out.println();
}
}
Output
When the JAXBContext is bootstrapped off of VolunteerSession obviously it has the necessary information.
When the JAXBContext is bootstraped off of the super class SessionRecord it doesn't pull in VolunteerSession. JAXB will automatically process metadata for super classes, but not subclasses. #XmlSeeAlso is usually used in this case to reference mapped subclasses.
VolunteerRecord contains an #XmlSeeAlso annotation that references VolunteerSession. Therefore VolunteerSession is processed as part of the JAXBContext and contains the necessary information when marshalled.
forum20908213.VolunteerSession
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<volunteerSession available="false" sessionId="0" open="false" night="false" description="Sunday 05:53-05:53 " setupTakedown="false"/>
forum20908213.SessionRecord
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sessionRecord sessionId="0" open="false" night="false" description="Sunday 05:53-05:53 " setupTakedown="false"/>
forum20908213.XMLResponse
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<volunteerSession available="false" sessionId="0" open="false" night="false" description="Sunday 05:53-05:53 " setupTakedown="false"/>
You have to list all of your subclasses in #XmlSeeAlso annotation of your parent class.
Related
my current code marshalls perfectly, and I get the element I want inside of my resulting XML. i.e. <food>Beef</food>
However, the problem comes when I have to unmarshall this back to a java object. Everything returns fine except the food variable. I originally did not have the XmlElement(required = true) on top, and the food element would always unmarshal back to null. Then, I added the required=true section and I am getting issues with the interface. I did some digging and from what I can gather, jaxb can't really unmarshal into an interface since it doesn't know the concrete type to marshall into.
Current error if this helps:
Can not set FoodInterface field BigPayload.food to
com.sun.org.apache.xerces.internal.dom.ElementNSImpl
My Java classes are as follows:
#XmlSeeAlso({MeatFoods.class, VeggieFoods.class})
#XmlType(name ="BigPayload", propOrder = //stuff goes here
#XmlRootElement(name = foodPayload)
public class BigPayload implements Payload{
#XmlElements({#XmlElement(type = MeatFoods.class),
#XmlElement(type = VeggieFoods.class),
#XmlElement(required = true)})
protected FoodInterface food;
protected Grade grade;
//grade/food setters and getters
}
#XmlTransient //If this isn't here, I get the jaxB cannot handle interfaces and no default constructor error
public interface FoodInterface{ //stuff here}
#XmlType(name = "MeatFoods")
#XmlEnum
public enum MeatFoods implements FoodInterface{
Chicken(1, Chicken)
Beef(2, Beef)
Pork(3, Pork)
int value;
String name;
#Override
public int getValue()
#Override
public String getName()
public static FoodInterface getEnumFromValue(int value){//gets stuff}
public static FoodInterface getEnumFromName(String name){//gets stuff}
}
I just wanted to know if that is correct, and there's no real good way to unmarshall an interface type. Is this true? I saw a lot of other questions were about marshalling interfaces, and the unmarshalling questions did not really get answers to my satisfaction. Any answer is appreciated, and I know this isn't a minimal reproducible example, but I'm more looking for a verbal answer instead of a code fix or anything. Although, if there's anything blatantly wrong in the code please let me know!
For the standard cases JAXB can only use (abstract) classes not interfaces.
Options that i can think of
You can use interfaces with #XmlAdapter. See example: [1]
Use Object for JAXB Bindings and expose the interface with casting. (Maybe add validation logic into the `afterUnmarshal(Unmarshaller u, Object parent). [2]
Bind a private field to #XmlAnyElement and do some further processing in afterUnmarshal(Unmarshaller, Object), add #XmlTransient to the target. See example: [3]
With some creativity there might be some other options. But i think all boil down to bascially: try to get to the "raw" parsing options and fill the interface reference manually.
[1]
public static interface Food {
String name();
}
public enum Veggie implements Food {
SALAD;
}
public static enum Meat implements Food {
CHICKEN;
}
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement
public static class UseInterface {
#XmlJavaTypeAdapter(FoodAdapter.class)
#XmlAttribute
private Food food;
public Food getFood() {
return food;
}
public void setFood(Food food) {
this.food = food;
}
}
public static class FoodAdapter extends XmlAdapter<String, Food> {
#Override
public Food unmarshal(String v) throws Exception {
try {
return Veggie.valueOf(v);
} catch (IllegalArgumentException e) {
}
try {
return Meat.valueOf(v);
} catch (IllegalArgumentException e) {
}
throw new IllegalArgumentException("Unknown Food:" + v);
}
#Override
public String marshal(Food v) throws Exception {
return v.name();
}
}
[2]
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement
public static class UseInterface {
#XmlElement
private Object food;
public Food getFood() {
return (Food) food;
}
public void setFood(Food food) {
this.food = food;
}
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
if (food != null && !(food instanceof Food)) {
throw new IllegalArgumentException("food is of wrong type: " + food.getClass().getName());
}
}
}
JAXBContext newInstance = JAXBContext.newInstance(UseInterface.class, Meat.class, Veggie.class);
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><useInterface><food xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"meat\">CHICKEN</food></useInterface>";
newInstance.createUnmarshaller().unmarshal(new StringReader(xml));
[3]
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement
public static class UseInterface {
#XmlAnyElement
private org.w3c.dom.Element foo;
#XmlTransient
private SomeInterface ifc
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
NamedNodeMap attributes = foo.getAttributes();
// do something with foo on DOM level to bind the subtree to an interface manually
}
}
I've been reading all the questions on this subject, but none of them relate to my problem. I have these classes (each of them in their own file):
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "Root")
public class Root {
#XmlElements({
#XmlElement(name="Child", type=ChildImpl.class),
#XmlElement(name="Child", type=ChildImpl2.class)
})
protected List<AbstractChild> children;
public List<AbstractChild> getChildren() {
if (children == null) {
children = new ArrayList<AbstractChild>();
}
return this.children;
}
}
#XmlTransient
public abstract class AbstractChild {
#XmlElement(name = "Other", required = true)
protected List<Other> others; // class Other is not important for my question, so I'll skip its implementation details
public List<Other> getOthers() {
if (others == null) {
others = new ArrayList<Other>();
}
return this.others;
}
}
#XmlRootElement(name = "Child")
public class ChildImpl extends AbstractChild {
// custom behavior
}
#XmlRootElement(name = "Child")
public class ChildImpl2 extends AbstractChild {
// different custom behavior
}
And then, I have the class that performs the unmarshalling:
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
result = (Root) jaxbUnmarshaller.unmarshal(new ByteArrayInputStream(fileContent)); // where fileContent is an instance of byte[]
Now, depending on our context, I want the unmarshaller to use a specific implementation of Child for the Root object... but that's where I'm struggling: I have no idea how to signal the unmarshaller to use a specific subclass for Child (in our files, the structure of Root, Child and Other is always the same. However, how we process Child depends on the source folder for each file).
I've tried passing the concrete class when creating the context -just for testing purposes- (e.g. JAXBContext.newInstance(Root.class, ChildImpl.class)), but for some reason, the unmarshaller always resolve to the class entered last in the #XmlElements array (In this case ChildImpl2).
I've also tried removing the #XmlElements annotation, but the unmarshaller doesn't know to process the Version elements since the parent class is abstract (that's also the reason why I added the #XmlTransient annotation; I have no interest in trying to instance AbstractChild)
Any ideas?
Thanks in advance!
If the structure in the xml-files is always the same, having an abstract class AbstractChild makes no sense (in my opinion). The logic should be elsewhere in your code, in a strategy or something like that.
But it is kind of possible:
Have an XmlElement representing the child.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "child")
public class Child {
#XmlElement(name = "name")
private String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
Have another Class like MyAbstractChild
public abstract class MyAbstractChild {
private final Child child;
public AbstractChild(final Child child) {
this.child = child;
}
public Child getChild() {
return child;
}
}
And subclasses for each behavior you want:
public class MyChildImpl extends MyAbstractChild {
public MyChildImpl(final Child child) {
super(child);
}
// custom behavior here
}
Then you can implement an XmlAdapter:
public class MyChildImpAdapter extends XmlAdapter<Child, MyAbstractChild> {
private final Class<? extends AbstractChild> implClass;
public MyChildImpAdapter(final Class<? extends MyAbstractChild> implClass){
this.implClass = implClass;
}
#Override
public MyAbstractChild unmarshal(final Child child) throws Exception {
if (MyChildImpl.class.equals(this.implClass)) {
return new MyChildImpl(child);
} else {
return new MyChildImpl2(child);
}
}
#Override
public Child marshal(final MyAbstractChild abstractChild) throws Exception {
return abstractChild.getChild();
}
}
Now you can use the new type MyAbstractChild in your root element:
#XmlJavaTypeAdapter(value = MyChildImpAdapter.class)
protected List<MyAbstractChild> children;
Finally you can train the unmarshaller to use your adapter of choice:
final JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
jaxbUnmarshaller.setAdapter(MyChildImpAdapter.class, new MyChildImpAdapter(MyChildImpl.class));
final InputStream inputStream = getClass().getResourceAsStream("some.xml");
final Root root = (Root) jaxbUnmarshaller.unmarshal(inputStream);
Now you have your Root-Element with MyChildImpl-Objects in the children.
But as I wrote in the beginning: there should be another option :)
In the below sample, the Data block inside A and the Data block inside B should be unmarshalled into different classes. Is this achievable using JAXB?
<Content>
<A>
<Data>
<Name></Name>
<Age></Age>
</Data>
</A>
<B>
<Data>
<MobilePhone></MobilePhone>
<WorkPhone></WorkPhone>
</Data>
</B>
</Content>
The Data inside A and the Data inside B represent different classes.The data inside A should be mapped to AData.class and the Data inside B should be mapped to BData.class.
Note: Marshalling is working fine. Any number of classes can have the same name tag. The generated xml contains the same tag for all those classes. In this case, AData and BData will both be written to XML as <Data> . But even the same marshalled xml cannot be unmarshalled again. I am hoping this can be solved by adding some additional annotations.
You just need to have the following:
#XmlAccessorType(XmlAccessType.FIELD)
public class A {
#XmlElement(name="Data")
private AData data;
}
#XmlAccessorType(XmlAccessType.FIELD)
public class B {
#XmlElement(name="Data")
private BData data;
}
#XmlRootElement(name="Content")
#XmlAccessorType(XmlAccessType.FIELD)
public class Content {
#XmlElement(name="A")
private A a;
#XmlElement(name="B")
private B b;
}
The solution that Blaise has posted will be a good way to tackle this if you know ahead of time the objects that Content will contain, such as here:
public class Content {
#XmlElement(name="A")
private A a;
#XmlElement(name="B")
private B b;
}
But another way you could do this is to have the data that could be contained in content be wrapped in a list of some supertype that A/B extend from, which results in XML that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Content>
<myContent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="a">
<Data>
<Name>Joe Smith</Name>
<Age>25</Age>
</Data>
</myContent>
<myContent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b">
<Data>
<MobilePhone>555-234-5678</MobilePhone>
<WorkPhone>555-555-5555</WorkPhone>
</Data>
</myContent>
</Content>
You can get this by annotating your classes like so:
#XmlRootElement(name = "Content")
#XmlAccessorType(XmlAccessType.FIELD)
public class Content {
#XmlElement
List<SomeSuperType> myContent;
public Content() {
}
public List<SomeSuperType> getMyContent() { return this.myContent; }
public void setMyContent(List<SomeSuperType> myContent ) { this.myContent = myContent; }
}
// class for A
#XmlRootElement(name = "A")
#XmlAccessorType(XmlAccessType.FIELD)
public class A extends SomeSuperType {
#XmlElement(name="Data")
AData data;
public A() {
data = new AData();
}
public void setName(String name) {
data.name = name;
}
public void setAge(int age) {
data.age = age;
}
public String getName() { return data.name; }
public int getAge() { return data.age; }
}
class AData {
#XmlElement(name = "Name")
String name;
#XmlElement(name = "Age")
int age;
}
// class for B
#XmlRootElement(name = "B")
#XmlAccessorType(XmlAccessType.FIELD)
public class B extends SomeSuperType {
#XmlElement(name = "Data")
BData data;
public B() {
data = new BData();
}
public void setMobilePhone(String mobilePhone) { data.mobilePhone = mobilePhone; }
public void setWorkPhone(String workPhone) { data.workPhone = workPhone; }
public String getMobilePhone() { return data.mobilePhone; }
public String getWorkPhone() { return data.workPhone; }
}
class BData {
#XmlElement(name="MobilePhone")
String mobilePhone;
#XmlElement(name="WorkPhone")
String workPhone;
public BData() {
}
}
I'm trying to implement all Java classes for handling the following XML code snippet:
<party date="2012-09-30">
<guest name="Albert">
<drink>wine</drink>
</guest>
</party>
I've wrote 3 classes:
Party.java:
package li.mnet.www.java.xml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "party")
public class Party {
#XmlAttribute(name = "date")
private String partyDate;
public Party() {}
public String getPartyDate() {return partyDate;}
public void setPartyDate(String partyDate) {
this.partyDate = partyDate;
}
}
Guest.java:
package li.mnet.www.java.xml;
import javax.xml.bind.annotation.XmlElement;
public class Guests {
private String name;
public Guests() {}
public void setGuestName(String name) {this.name = name;}
#XmlElement(name = "name")
public String getGuestName() {return name;}
}
PartyRunner.java:
package li.mnet.www.java.xml;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class PartyRunner {
public static void main(String[] args) {
Party party = new Party();
Guests guest = new Guests();
party.setPartyDate("2012-09-03");
guest.setGuestName("Albert");
JAXBContext context;
try {
context = JAXBContext.newInstance(Party.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(party, System.out);
} catch (JAXBException e) {e.printStackTrace();}
}
}
After running the application i get following console output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<party date="2012-09-03"/>
What do i have to change, that class Guest.java gets printed out too?
Thanks a lot for your support!
When you're trying to marshal some data through JAXB, you'll give it an instance of your class (here is Party) and it will traverse your object and all of its attributes and tries to serialize them to the final output using hints provided by JAXB annotations.
Remember that JAXB ignores properties of the class which has no JAXB annotation. Also You can it tell whether to generate an XML Element or XML Attribute for given class property. You can use these annotations on properties or their getter methods.
In your example, you want to have a guest element inside party element. In your main method (in PartyRunner), you're marshaling an instance of Party class, but this class has no reference to your Guests class. Creating an instance of Guests class wouldn't be enough. You have to create a logical relationship between two classes and annotate them to make it possible to generate an appropriate XML. So your Party class should be something like this:
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "party")
public class Party {
#XmlAttribute(name = "date")
private String partyDate;
#XmlElement(name="guest")
private Guests guests;
public Party() {}
public String getPartyDate() {return partyDate;}
public void setPartyDate(String partyDate) {
this.partyDate = partyDate;
}
public Guests getGuests() {
return guests;
}
public void setGuests(Guests guests) {
this.guests = guests;
}
}
If you run the PartyRunner again you'll have something like this in your output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<party>
<partyDate>2012-09-03</partyDate>
<guest>
<name>Albert</name>
</guest>
</party>
As you can see, there is an inner element named name in your guests element. This is due to the annotation you've specified for getGuestName method in your Guests class. In order to make JAXB to generate an XML attribute for this property (instead of an XML element), you need to change the JAXB annotation in your Guests class too. You have annotated the getGuestName method as #XmlElement. This will cause to generate an XML element. If you change it to #XmlAttribute and run the PartyRunner again, you'll have this in your output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<party date="2012-09-03">
<guest name="Albert"/>
</party>
Also in your sample XML you have a drink element inside your guests property. Same is true for drink property. The drink could be a String property in your Guests class annotated as #XmlAttribute(name = "drink"). So your final Guests class to generate the XML mentioned at the beginning of your question should be something like this:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
public class Guests {
private String name;
private String drinkType;
public Guests(){}
public void setGuestName(String name) {this.name = name;}
#XmlAttribute(name = "name")
public String getGuestName() {return name;}
#XmlElement(name = "drink")
public String getDrinkType() {
return drinkType;
}
public void setDrinkType(String drinkType) {
this.drinkType = drinkType;
}
}
and your PartyRunner should initialize the drink property to something like wine:
public static void main(String[] args) {
Party party = new Party();
Guests guest = new Guests();
party.setPartyDate("2012-09-03");
guest.setGuestName("Albert");
guest.setDrinkType("wine");
party.setGuests(guest);
JAXBContext context;
try {
context = JAXBContext.newInstance(Party.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(party, System.out);
} catch (JAXBException e) {e.printStackTrace();}
}
I think the party class should contain a guest (or list of guests if you want more)
public class Party {
#XmlAttribute(name = "date")
private String partyDate;
private Guest guest;
public Party() {}
public String getPartyDate() {return partyDate;}
public void setPartyDate(String partyDate) {
this.partyDate = partyDate;
}
// getter and setter for guest
}
set the guest of the party object then marshal the party object.
Also change the XmlElement annotiantion to XmlAttribute in the guest class at the name.
I'm using JAXB to unmarshal some xml into an object(s).
I have a class which inherit from an abstract class. I've marked the abstract class as #XmlTransient. Then using XMLType PropOrder I can access the properties in the abstract class like so:
#XmlType( propOrder = { "id"...
Cool. Problem is sometimes it isn't an element that I want to access but rather an attribute. Normally you would define such a property using #XMLAttribute to indicate the value is stored in an xml attribute and not an element. But given the fact that I've already used XMLTransient on the abstract class where 'id' is defined, JAXB complains when I try to mark the field as #XMLAttribute.
JAXB is complaining that I'm trying to access/return two fields of with the same name.
Can anyone please point me in the right direction? I'm building for GAE so I dn't really want to use any other libraries.
Thanks in advance!
Below are a couple of things you can do:
Java Model
Foo
You can annotate the property on the parent class with #XmlAttribute.
import javax.xml.bind.annotation.*;
#XmlTransient
public class Foo {
private String att1;
private String att2;
#XmlAttribute
public String getAtt1() {
return att1;
}
public void setAtt1(String att1) {
this.att1 = att1;
}
public String getAtt2() {
return att2;
}
public void setAtt2(String att2) {
this.att2 = att2;
}
}
Bar
You can override the property on the subclass and annotate it with #XmlAttribute.
import javax.xml.bind.annotation.*;
#XmlRootElement
public class Bar extends Foo {
#Override
#XmlAttribute
public String getAtt2() {
return super.getAtt2();
}
#Override
public void setAtt2(String att2) {
super.setAtt2(att2);
}
}
Demo Code
Demo
Here is some demo code you can run to show that everything works.
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Bar.class);
Bar bar = new Bar();
bar.setAtt1("a");
bar.setAtt2("b");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(bar, System.out);
}
}
Output
Below is the output from running the demo code:
<?xml version="1.0" encoding="UTF-8"?>
<bar att1="a" att2="b"/>