Unmarshal XML and store into Multimapping - java

This is my xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<input1>
<concept name="Rad order">
<input>varReasonForexam=Infection, post-operative;varReasonID=19666904</input>
</concept>
<concept name="Inpatient Encounter">
<input>varFirstName=park123a;varLastName=sssrk123a;varSex=Male</input>
</concept>
</input1>
This is my Concept.java class
public class Concept {
private String input;
private String name;
public Concept() {}
public String getinput() {
return input;
}
public void setinput(String input){
this.input = input;
}
#XmlAttribute
public String getname() {
return name;
}
public void setname(String name){
this.name = name;
}
}
This is my Input1.java class
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Input1 {
private List<Concept> concept;
#XmlElement
public List<Concept> getconcept() {
return concept;
}
public void setconcept(List<Concept> concept) {
this.concept = concept;
}
}
This is main class RefactorClassArray1.java
import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.util.ArrayList;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Set;
public class RefactorClassArray1 {
public static void main(String[] args) {
ArrayList<String> thisIsAStringArray = new ArrayList<String>();
Multimap<String, String> strMapVariables = ArrayListMultimap.create();
try {
JAXBContext context = JAXBContext.newInstance(Input1.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Input1 input = (Input1) unmarshaller.unmarshal(new File("varFile.xml"));
List<Concept> list=input.getconcept();
int isize = list.size();
for(int i = 0; i < isize; i++)
{
Concept concept = list.get(i);
String strconname = concept.getname();
String strinput= concept.getinput();
String [] strarrinput = strinput.split(";");
int arrsize = strarrinput.length ;
String strinputval ;
for (int j=0; j<arrsize; j++) {
strinputval = strarrinput[j];
strMapVariables.put(strconname, strinputval);
}
}
Set<String> keys = strMapVariables.keySet();
for(String key: keys) {
thisIsAStringArray.add(key);
}
System.out.println("thisIsAStringArray:" + thisIsAStringArray);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Output i am getting is
strMapVariables:{Rad order=[varReasonForexam=Infection, post-operative, varReasonID=19666904], Inpatient Encounter=[varFirstName=park123a, varLastName=sssrk123a, varSex=Male]}
thisIsAStringArray:[Rad order, Inpatient Encounter]
My question is like this:
If i add one more input under concept name="Rad order" in XML,
This is my new xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<input1>
<concept name="Rad order">
<input>varReasonForexam=Infection, post-operative;varReasonID=19666904</input>
<input>varReasonForpain=Ipain, pelvic;varID=19666905<input>
</concept>
<concept name="Inpatient Encounter">
<input>varFirstName=park123a;varLastName=sssrk123a;varSex=Male</input>
</concept>
</input1>
expected strMapVariables output like below:
strMapVariables:{Rad order=[varReasonForexam=Infection, post-operative, varReasonID=19666904], Rad order=[varReasonForpain=Ipain, pelvic;varID=19666905] Inpatient Encounter=[varFirstName=park123a, varLastName=sssrk123a, varSex=Male]}
I want to use JAXB and mapping only, post code needs the output as collection of mapping. How to achieve this?

Related

Mapping XML to Object with same tag names but different attributes

I am trying to convert the below XML string to a Java object using JAXB and eclipse persistence oxm annotations package.
<output>
<rtEvent>
<eventData name="tcppayload">
<data>111111-000000-111111</data>
</eventData>
<eventData name="text">
<data>ABCD</data>
</eventData>
</rtEvent>
</output>
However, the de-serialization does not seem to work. Can someone point out what I might be doing wrong.
Below is the class i'm using to deserialize the string into an object
#XmlRootElement(name = "output")
#XmlAccessorType(XmlAccessType.FIELD)
public class CameraTriggerOutput {
#XmlPath("/rtEvent/eventData[#name=tcppayload]/data/text()")
private String data;
public void toXml() {
try {
JAXBContext ctx = JAXBContext.newInstance(CameraTriggerOutput.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(this, System.out);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
After running I get the following output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><output/>
I provide below the code with pure Jaxb, you can try.
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "eventData")
public class EventData {
private String name;
private String data;
#XmlElement(name = "data")
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
#XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "rtEvent")
public class RtEvent {
private List<EventData> edataList;
#XmlElement(name = "eventData")
public List<EventData> getEdataList() {
return edataList;
}
public void setEdataList(List<EventData> edataList) {
this.edataList = edataList;
}
}
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "output")
public class Output {
private RtEvent rtEvent;
public RtEvent getRtEvent() {
return rtEvent;
}
public void setRtEvent(RtEvent rtEvent) {
this.rtEvent = rtEvent;
}
public static void main(String[] args) {
try {
EventData eData1 = new EventData();
eData1.setData("111111-000000-111111");
eData1.setName("tcppayload");
EventData eData2 = new EventData();
eData2.setData("ABCD");
eData2.setName("text");
List<EventData> eDataList = new ArrayList<>();
eDataList.add(eData1);
eDataList.add(eData2);
RtEvent rtEvent = new RtEvent();
rtEvent.setEdataList(eDataList);
Output output = new Output();
output.setRtEvent(rtEvent);
JAXBContext ctx = JAXBContext.newInstance(Output.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(output, System.out);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You Jaxb only as it is part of java, there is no need to include any other annotations. You can make individual classes in your ide and you can test the class Output which has a main method.

Null List returning for Multiple Occurrence sections in JAXB

Hi i'm new to JAXB Conversions.
I'm Unmarshalling an xml into java objects. For single occurrence sections there is no issue, but for multiple occurrence not able to map properly. Each time I'm getting null list for multiple occurrence section.
Please suggest me any useful url's or suggest me changes need to be done.
XML ::
<?xml version="1.0" encoding="UTF-8"?>
<designTheory>
<Administartor>
<circuitId>67565675476</circuitId>
<processId>567855</processId>
<version>01</version>
<circuitReferenceValue>ciruit-0001</circuitReferenceValue>
<property>cal-circuit</property>
</Administartor>
<designSec>
<priloc>priloc</priloc>
<secloc>secloc</secloc>
<remarks>remarks field</remarks>
</designSec>
<designNotes>
<notesNumber>1</notesNumber>
<notes>designNotes 1</notes>
</designNotes>
<designNotes>
<notesNumber>2</notesNumber>
<notes>designNotes 2</notes>
</designNotes>
<designNotes>
<notesNumber>3</notesNumber>
<notes>designNotes 3</notes>
</designNotes>
<designNotes>
<notesNumber>4</notesNumber>
<notes>designNotes 4</notes>
</designNotes>
</designTheory>
Code Snippets are as below :
DesignTheory.java
package org.manjunath.jaxbconversions.beans;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "designTheory")
public class DesignTheory {
#XmlElement(name = "Administartor", required = true)
private Administartor admin;
#XmlElement(name = "designSec", required = true)
private DesignSec designSec;
#XmlElementWrapper
#XmlElementRef(name = "designNotes")
private List<JAXBElement<DesignNotes>> designNotesList;
public void setAdministartor(Administartor admin){
this.admin = admin;
}
public Administartor getAdministartor() {
return admin;
}
public DesignSec getDesignSec() {
return designSec;
}
public void setDesignSec(DesignSec designSec) {
this.designSec = designSec;
}
public List<JAXBElement<DesignNotes>> getDlrnotes() {
return designNotesList;
}
public void setDlrnotes(List<JAXBElement<DesignNotes>> designNotesList) {
this.designNotesList = designNotesList;
}
}
Administartor.java
package org.manjunath.jaxbconversions.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "Administartor")
public class Administartor {
#XmlElement(name = "circuitId")
private String circuitId;
#XmlElement(name = "processId")
private String processId;
#XmlElement(name = "version")
private String version;
#XmlElement(name = "circuitReferenceValue")
private String circuitReferenceValue;
#XmlElement(name = "property")
private String property;
public String getcircuitId() {
return circuitId;
}
public void setcircuitId(String circuitId) {
this.circuitId = circuitId;
}
public String getprocessId() {
return processId;
}
public void setprocessId(String processId) {
this.processId = processId;
}
public String getVer() {
return version;
}
public void setVer(String version) {
this.version = version;
}
public String getcircuitReferenceValue() {
return circuitReferenceValue;
}
public void setcircuitReferenceValue(String circuitReferenceValue) {
this.circuitReferenceValue = circuitReferenceValue;
}
public String getproperty() {
return property;
}
public void setproperty(String property) {
this.property = property;
}
}
DesignSec.java
package org.manjunath.jaxbconversions.beans;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "designSec")
public class DesignSec {
#XmlElement (name = "priloc")
private String priloc;
#XmlElement (name = "secloc")
private String secloc;
#XmlElement (name = "remarks")
private String remarks;
public String getpriloc() {
return priloc;
}
public void setpriloc(String priloc) {
this.priloc = priloc;
}
public String getSecloc() {
return secloc;
}
public void setSecloc(String secloc) {
this.secloc = secloc;
}
public String getremarks() {
return remarks;
}
public void setEcspc(String remarks) {
this.remarks = remarks;
}
}
DesignNotes.java
package org.manjunath.jaxbconversions.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "designNotes")
#XmlAccessorType(XmlAccessType.FIELD)
public class DesignNotes {
#XmlElement (name = "notesNumber")
private String notesNumber;
#XmlElement (name = "notes")
private String notes;
public String getnotesNumber() {
return notesNumber;
}
public void setnotesNumber(String notesNumber) {
this.notesNumber = notesNumber;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
And I found somewhere the #XmlRegistry and #XmlElementDecl will solve my problem.
But I'm not so good with these annotations, but I tried by using ObjectFactory.java class. No use of this class
ObjectFactory.java
package org.manjunath.jaxbconversions.factory;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import org.manjunath.jaxbconversions.beans.DesignNotes;
#XmlRegistry
public class ObjectFactory {
private final static QName _DesignNotes_QNAME = new QName("designNotes");
public ObjectFactory(){
}
#XmlElementDecl(name="designNotes")
public JAXBElement<DesignNotes> createDesignNotes(DesignNotes value) {
return new JAXBElement<DesignNotes>(_DesignNotes_QNAME, DesignNotes.class, value);
}
}
Please suggest me to solve this problem
In your class DesignTheory the definition
#XmlElementWrapper
#XmlElementRef(name = "designNotes")
private List<JAXBElement<DesignNotes>> designNotesList;
is wrong.
In your XML you have
<designNotes>
...
</desinNotes>
<designNotes>
...
</designNotes>
...
But you do not have an additional wrapper around these <designNotes> like this
<designNotesList>
<designNotes>
...
</desinNotes>
<designNotes>
...
</designNotes>
...
<designNotesList>
That's why you need to remove the #XmlElementWrapper annotation.
And you should change its type from List<JAXBElement<DesignNotes>>
to List<DesignNotes>. So you end up with
#XmlElementRef(name = "designNotes")
private List<DesignNotes> designNotesList;
Also change the associated getter and setter from List<JAXBElement<DesignNotes>>
to List<DesignNotes>.
Then you don't need the ObjectFactory anymore and can remove it completely.
I verified the corrected classes with your XML and the following test-code
#Test
public void testUnmarshall() throws Exception {
JAXBContext context = JAXBContext.newInstance(DesignTheory.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File file = new File("design-theory.xml");
DesignTheory designTheory = (DesignTheory) unmarshaller.unmarshal(file);
Assert.assertNotNull(designTheory.getDlrnotes());
Assert.assertEquals(4, designTheory.getDlrnotes().size());
}
The unmarshalled designTheory correctly has a non-null List<DesignNotes> with 4 elements.

Converting XML to Java Object using jaxb (Unmarshal)

I am trying to convert my below xml to java object.
This is my xml:
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hl7-org:v3" xmlns:sdtc="urn:hl7-org:sdtc" xmlns:voc="urn:hl7-org:v3/voc">
<confidentialityCode code="" codeSystem=""/>
<languageCode code="en-"/>
<recordTarget>
<patientRole>
<id root="" extension=""/>
<telecom value="" use=""/>
<providerOrganization>
<id root="" extension=""/>
<id root="" extension=""/>
<name>Something</name>
<telecom value=""/>
<addr use="">
<state></state>
<city></city>
<postalCode></postalCode>
<streetAddressLine>2121</streetAddressLine>
</addr>
</providerOrganization>
</patientRole>
</recordTarget>
</ClinicalDocument>
I need to get the value of "name" under "providerOrganization".
Below are my Java classes.
ClinicalDocument.java
package com.biclinical.data;
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="ClinicalDocument", namespace="urn:hl7-org:v3")
public class ClinicalDocument {
#XmlElement(name="recordTarget")
private List<RecordTarget> recordTarget;
public List<RecordTarget> getRecordTarget() {
return recordTarget;
}
public void setRecordTarget(List<RecordTarget> recordTarget) {
this.recordTarget = recordTarget;
}
#Override
public String toString() {
return "ClinicalDocument [recordTarget=" + recordTarget + "]";
}
}
RecordTarget.java
package com.biclinical.data;
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="recordTarget")
public class RecordTarget {
#XmlElement(name="patientRole")
private List<PatientRole> patientRole;
public List<PatientRole> getPatientRole() {
return patientRole;
}
public void setPatientRole(List<PatientRole> patientRole) {
this.patientRole = patientRole;
}
#Override
public String toString() {
return "RecordTarget [patientRole=" + patientRole +"]";
}
}
PatientRole.java
package com.biclinical.data;
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "patientRole")
public class PatientRole {
/*#XmlElement(name = "id")
private String id;
Double root;
String extension;*/
#XmlElement(name="providerOrganization")
private List<ProviderOrganization> providerOrganization;
public List<ProviderOrganization> getProviderOrganization() {
return providerOrganization;
}
public void setProviderOrganization(List<ProviderOrganization> providerOrganization) {
this.providerOrganization = providerOrganization;
}
}
ProviderOrganisation.java
package com.biclinical.data;
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="providerOrganization")
public class ProviderOrganization {
#XmlElement(name="name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Patient [Name=" + name + "]";
}
}
XMLFileParserSAXUtility.java
public class XMLFileParserSAXUtility extends DefaultHandler {
public static void main(String[] args) {
try {
File file = new File("C:/Users/shivendras/Desktop/Patient19999_Test_Organization1.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(new Class[] {ClinicalDocument.class,RecordTarget.class,PatientRole.class,ProviderOrganization.class});
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ClinicalDocument clinicalDocument = (ClinicalDocument) jaxbUnmarshaller.unmarshal(file);
//clinicalDocument.getRecordTarget()
String s = ((File) ((PatientRole) ((RecordTarget) clinicalDocument.getRecordTarget()).getPatientRole()).getProviderOrganization()).getName();
System.out.println(s);
} catch (JAXBException e) {
e.printStackTrace();
}
}
I get the result as
Exception in thread "main" java.lang.NullPointerException
at com.biclinical.util.XMLFileParserSAXUtility.main(XMLFileParserSAXUtility.java:27)
And if i try to print syso(clinicalDocument);
Result is ClinicalDocument [recordTarget=null]
Please help me out here!
I think you add the namespace to your #XmlElement :
#XmlElement(name="patientRole")
private List<PatientRole> patientRole;
Should be :
#XmlElement(name="patientRole",namespace="urn:hl7-org:v3")
private List<PatientRole> patientRole;
If you're having any other null in your objects, try adding the namespace.
Also, #XmlRootEntity is only necessary for your root element, in this case your ClinicalDocumentclass, and you only need to give the root class to your JAXBContext :
JAXBContext jaxbContext = JAXBContext.newInstance(ClinicalDocument.class);

JAXB - How to create the XML element with attributes from Map?

I need something like this -
<Token>
<HighLevel info-1="" info-2=""/>
<LowLevel>
<LowLevel info-key="" info-value=""/>
<LowLevel info-key="" info-value=""/>
....
</LowLevel>
</Token >
I've the Map for LowLevel element, whose entries I want to populate like above XML.
What could be the way to encapsulate/bind this using JAXB?
You could use a custom adapter for this. Example
//Token.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement
class LowLevelToken {
#XmlAttribute(name = "info-key")
public String key;
#XmlAttribute(name = "info-value")
public String value;
private LowLevelToken() {}
public LowLevelToken(String key, String value) {
this.key = key;
this.value = value;
}
}
#XmlRootElement
class HighLevelToken {
#XmlAttribute(name = "info-1")
public String info1;
#XmlAttribute(name = "info-2")
public String info2;
private HighLevelToken() {}
public HighLevelToken(String info1, String info2) {
this.info1 = info1;
this.info2 = info2;
}
}
class TokenWrapper {
#XmlElement(name="LowLevel")
public List<LowLevelToken> tokens = new ArrayList<LowLevelToken>();
}
class TokenAdapter extends XmlAdapter<TokenWrapper, Map<String, String>> {
#Override
public TokenWrapper marshal(Map<String, String> lowlevelTokens)
throws Exception {
TokenWrapper wrapper = new TokenWrapper();
List<LowLevelToken> elements = new ArrayList<LowLevelToken>();
for (Map.Entry<String, String> property : lowlevelTokens.entrySet()) {
elements.add(new LowLevelToken(property.getKey(), property.getValue()));
}
wrapper.tokens = elements;
return wrapper;
}
#Override
public Map<String, String> unmarshal(TokenWrapper tokenWrapper) throws Exception {
Map<String, String> tokens = null;
if(tokenWrapper != null && tokenWrapper.tokens != null && !tokenWrapper.tokens.isEmpty()){
tokens = new HashMap<String, String>();
for(LowLevelToken token : tokenWrapper.tokens){
tokens.put(token.key, token.value);
}
}
return tokens;
}
}
#XmlRootElement(name = "Token")
public class Token {
HighLevelToken highLevel;
Map<String, String> lowLevel;
public HighLevelToken getHighLevel() {
return highLevel;
}
#XmlElement(name = "HighLevel")
public void setHighLevel(HighLevelToken highLevel) {
this.highLevel = highLevel;
}
public Map<String, String> getLowLevel() {
return lowLevel;
}
#XmlElement(name = "LowLevel")
#XmlJavaTypeAdapter(TokenAdapter.class)
public void setLowLevel(Map<String, String> lowLevel) {
this.lowLevel = lowLevel;
}
}
A sample program
import java.util.HashMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Token token = new Token();
token.setHighLevel(new HighLevelToken("1", "2"));
token.setLowLevel(new HashMap<String, String>() {{ put("LK1", "LV1"); put("LK2", "LV2"); put("LK2", "LV2"); }});
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Token.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(token, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
This generates
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Token>
<HighLevel info-1="1" info-2="2"/>
<LowLevel>
<LowLevel info-key="LK2" info-value="LV2"/>
<LowLevel info-key="LK1" info-value="LV1"/>
</LowLevel>
</Token>

JAVA/JAXB Help needed

This is gonna be lengthy but I need some enlightenment. I'm new to JAXB so please be lenient with me.
CourseApp:
package Courses;
import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class CoursesApp {
public static void main(String[] args) {
Courselist courselist = new Courselist();
courselist.setclassType("Lecture");
courselist.setcourseCode("2002");
courselist.setgroupIndex("1");
courselist.setprofessor("Professor James");
try{
File file = new File("C:\\Courselist.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Courselist.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(courselist, file);
jaxbMarshaller.marshal(courselist, System.out);
}catch(JAXBException e)
{
e.printStackTrace();
}
}
}
Courselist:
package Courses;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Courselist {
String courseCode;
String classType;
String groupIndex;
String professor;
public String getcourseCode() {
return courseCode;
}
#XmlElement
public void setcourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getclassType() {
return classType;
}
#XmlElement
public void setclassType(String classType) {
this.classType = classType;
}
public String getgroupIndex() {
return groupIndex;
}
#XmlElement
public void setgroupIndex(String groupIndex) {
this.groupIndex = groupIndex;
}
public String getprofessor() {
return professor;
}
#XmlElement
public void setprofessor(String professor) {
this.professor = professor;
}
}
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <courselist>
<classType>Lecture</classType>
<courseCode>2002</courseCode>
<groupIndex>1</groupIndex>
<professor>Professor James</professor>
</courselist>
What I want is to create another instance of courselist within the same XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <courselist>
-<course>
<classType>Lecture</classType>
<courseCode>2002</courseCode>
<groupIndex>1</groupIndex>
<professor>Professor James</professor>
</course>
-<course>
<classType>Lecture</classType>
<courseCode>2003</courseCode>
<groupIndex>2</groupIndex>
<professor>Professor John</professor>
</course>
</courselist>
I would recommend to have one member in CourseList: List<Course> when Course will include all the members currently in CourseList.
This is the code:
#XmlRootElement
public class Courselist {
#XmlElement List<Course> course = new ArrayList<Course>();
}
Courselist
As oshai answered I would have a model with two classes Courselist and Course. Below is what the Courselist class would look like. To match Java programming conventions the package name is normally lower case. Also it is also often based on a domain name (such as com.example.courses). By default JAXB (JSR-222) implementations look for metadata on the property (get or set methods) so I've put them there (see: http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html).
package courses;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Courselist {
List<Course> courses;
#XmlElement(name="course")
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
Course
The information you had in the Courselist class I have moved to a new Course class. JAXB is configuration by exception so you only need to add annotations where you wish the XML representation to differ from the default. In your use case you don't need any annotations on this class (see: http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html). I have fixed the casing on your property methods to match the normal Java coding conventions.
package courses;
public class Course {
String courseCode;
String classType;
String groupIndex;
String professor;
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getClassType() {
return classType;
}
public void setClassType(String classType) {
this.classType = classType;
}
public String getGroupIndex() {
return groupIndex;
}
public void setGroupIndex(String groupIndex) {
this.groupIndex = groupIndex;
}
public String getProfessor() {
return professor;
}
public void setProfessor(String professor) {
this.professor = professor;
}
}

Categories