Hi, I'm trying to follow the XmlAdapter example in Koshuke's blog here:
http://weblogs.java.net/blog/kohsuke/archive/2005/04/xmladapter_in_j.html
and when I try to marshall the Brochure class, it results in xml output like
this:
<brochure>
<course>
<item id="c0">
<name>Course 0</name>
</item>
<item id="c1">
<name>Course 1</name>
</item>
</course>
</brochure>
instead of
<brochure>
<course id="c0">
<name>Course 0</name>
</item>
<course id="c1">
<name>Course 1</name>
</item>
</brochure>
Can you please help me understand what I'm doing wrong? Below is the rest of
the code:
Brochure.java:
@XmlRootElement(name="brochure")
public class Brochure {
@XmlJavaTypeAdapter(CourseListAdapter.class)
@XmlElement(name="course")
Map<String,Course> courses;
public Brochure() {
courses = new HashMap<String, Course>();
}
}
Course.java
public class Course {
@XmlAttribute
String id;
@XmlElement
String name;
}
CourseListAdapter
public class CourseListAdapter extends XmlAdapter<Course[],
Map<String,Course>> {
public Map<String,Course> unmarshal( Course[] value ) {
Map<String,Course> r = new HashMap<String,Course>();
for( Course c : value )
r.put(c.id,c);
return r;
}
public Course[] marshal( Map<String,Course> value ) {
return value.values().toArray(new Course[value.size()]);
}
Test class:
public class Main {
@Test public void test() throws Exception {
JAXBContext jc = JAXBContext.newInstance(Brochure.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Brochure b = new Brochure();
for (int i=0; i<2; i++) {
Course c = getCourse(i);
b.courses.put(c.id, c);
}
m.marshal(b, System.out);
}
public Course getCourse(int i) {
Course c1 = new Course();
c1.id="c" + i;
c1.name="Course " + i;
return c1;
}
}
}
Thanks in advance!
Murali
--
View this message in context: http://www.nabble.com/XmlJavaTypeAdapter-help-tp19127284p19127284.html
Sent from the java.net - jaxb users mailing list archive at Nabble.com.