JAXB map to object insteadof string - java

I have the following XML:
<game name="m1itskow" sourcefile="maygay1bsw.c" ismechanical="yes" cloneof="m1itsko" romof="m1itsko">
<description>It's A Knockout (Maygay) (M1A/B) (set 24)</description>
<year>199?</year>
<manufacturer>Maygay</manufacturer>
</game>
Today I have manufacturer as a String inside Game class, but I need to map to a Manufacturer class, how should I do it? Is it possible? thanks.
edit: The XML cannot be changed because this is a generated file by a 3rd party tool.

Made changes in xml structure
XML
<?xml version="1.0" encoding="UTF-8"?>
<game name="m1itskow" sourcefile="maygay1bsw.c" ismechanical="yes" cloneof="m1itsko" romof="m1itsko">
<description>It's A Knockout (Maygay) (M1A/B) (set 24)</description>
<year>199?</year>
<manufacturer>
<manufacturer-name>Maygay</manufacturer-name>
</manufacturer>
</game>
POJO game and manufacturer...
game.java
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class game {
private String name;
private String sourcefile;
private String ismechanical;
private String cloneof;
private String romof;
private String description;
private String year;
private Manufacturer manufacturer=new Manufacturer();
public game() {}
#XmlAttribute
public String getIsmechanical() {
return ismechanical;
}
public void setIsmechanical(String ismechanical) {
this.ismechanical = ismechanical;
}
#XmlAttribute
public String getCloneof() {
return cloneof;
}
public void setCloneof(String cloneof) {
this.cloneof = cloneof;
}
#XmlAttribute
public String getRomof() {
return romof;
}
public void setRomof(String romof) {
this.romof = romof;
}
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlAttribute
public String getSourcefile() {
return sourcefile;
}
public void setSourcefile(String sourcefile) {
this.sourcefile = sourcefile;
}
#XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#XmlElement
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
#XmlElement(name="manufacturer")
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer=manufacturer;
}
}
manufacturer.java
i
mport java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="manufacturer")
public class Manufacturer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String Name;
#XmlElement(name="manufacturer-name")
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
main.java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class SampleTest {
public static void main(String[] args) {
try {
File file = new File("employee.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(game.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
game e=(game) jaxbUnmarshaller.unmarshal(file);
System.out.println(e.getManufacturer().getName());
}
catch (JAXBException e) {
e.printStackTrace();
}
}
}

Related

Get elements as list

I have this JAXB component which I would like to get as a list:
#XmlRootElement(name = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElement(name = "transaction_types")
public TransactionTypes transactionTypes;
}
public class TransactionTypes {
#XmlElement(name = "transaction_type")
public String transaction_type;
#XmlAttribute
public String name;
public String getTransaction_type() {
return transaction_type;
}
public void setTransaction_type(String transaction_type) {
this.transaction_type = transaction_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
XML structure:
<payment>
<transaction_types>
<transaction_type name="type1"/>
<transaction_type name="type2"/>
<transaction_type name="type3"/>
</transaction_types>
</payment>
The question is how I can get all transaction types as a list?
Can you give me some idea how should I modify the JAXB Object?
EDIT:
I tried this
#XmlRootElement(name = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElementWrapper(name = "transaction_types")
public List<TransactionTypes> transactionTypes;
}
Inner object which will hold the list:
public class TransactionTypes {
#XmlElement(name = "transaction_type")
public String transaction_type;
#XmlAttribute
public String name;
public String getTransaction_type() {
return transaction_type;
}
public void setTransaction_type(String transaction_type) {
this.transaction_type = transaction_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
To get all the transaction_type as a list, I have somewhat modified your code. I have introduced a new class TransactionList which will contain the list of transaction_type
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 = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElement(name = "transaction_types")
public TransactionList transactionList;
public Transaction() {
super();
}
#Override
public String toString() {
return "Transaction [TransactionList=" + transactionList + "]";
}
}
TransactionList class
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.FIELD)
public class TransactionList {
#XmlElement(name = "transaction_type")
public List<TransactionType> transactionType;
public TransactionList(List<TransactionType> transactionTypes) {
transactionType = transactionTypes;
}
public TransactionList() {
super();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (TransactionType transactionType : transactionType) {
sb.append(transactionType + "\n");
}
return sb.toString();
}
}
TransactionType class
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.FIELD)
public class TransactionType {
#XmlElement(name = "transaction_type")
private String transaction_type;
#XmlAttribute
private String name;
public TransactionType(String transaction_type, String name) {
this.transaction_type = transaction_type;
this.name = name;
}
public TransactionType() {
}
public String getTransaction_type() {
return transaction_type;
}
public void setTransaction_type(String transaction_type) {
this.transaction_type = transaction_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "TransactionTypes [transaction_type=" + transaction_type + ", name=" + name + "]";
}
}
main method
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Transaction.class);
Unmarshaller um = context.createUnmarshaller();
Transaction transaction = (Transaction) um.unmarshal(new FileReader(FILE));
System.out.println(transaction);
}
You can also check the output by directly changing the variable transactionType to List in Transaction table and assigning XMLElementWrapper annotation to it
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "payment")
#XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
#XmlElementWrapper(name = "transaction_types")
public List<TransactionType> transactionType;
public Transaction() {
}
}

Not able to extract only selected Tag values using Jaxb in Java

I've a very big XML string. Im posting here only part of the XML object. I'm trying to convert this XML to Java object. My first question is, should I need to create Java object of total XML tag values or can I have create the Java object of only selected inner XML objects? Please find my XML string.
<DATAPACKET REQUEST-ID = "2">
<HEADER>
<RESPONSE-TYPE CODE="1" DESCRIPTION="Response DataPacket"/>
<SEARCH-RESULT-LIST>
<SEARCH-RESULT-ITEM>
<NAME MATCHED="TRUE"/>
</SEARCH-RESULT-ITEM>
</SEARCH-RESULT-LIST>
</HEADER>
<BODY>
<CONS_SCORE>
<SCORE>0</SCORE>
<REASON1>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON1>
<REASON2>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON2>
<REASON3>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON3>
<REASON4>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON4>
</CONS_SCORE>
<CONSUMER_PROFILE2>
<CONSUMER_DETAILS2>
<RUID>1234</RUID>
<NAME>ABC</NAME>
<DATE_OF_BIRTH>1980-03-03T00:00:00+03:00</DATE_OF_BIRTH>
<GENDER>001</GENDER>
</CONSUMER_DETAILS2>
<ID_DETAILS2>
<SLNO>1</SLNO>
<SOURCE_ID>001</SOURCE_ID>
<ID_VALUE>2806</ID_VALUE>
<EXP_DATE>2018-07-13T00:00:00+03:00</EXP_DATE>
</ID_DETAILS2>
</CONSUMER_PROFILE2>
</BODY>
</DATAPACKET>
In the above object, I want to fetch only CONSUMER_PROFILE2 object. Here is my Dto class
#XmlRootElement(name = "DATAPACKET")
public class ConsumerProfileDto {
private ConsumerDetailsDto CONSUMER_DETAILS2;
private IdDetailsDto ID_DETAILS2;
public ConsumerDetailsDto getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetailsDto cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetailsDto getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetailsDto iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
CONSUMER_DETAILS2 class
#XmlRootElement(name = "CONSUMER_DETAILS2")
public class ConsumerDetailsDto {
private String NAME;
private String DATE_OF_BIRTH;
private String GENDER;
private String NATIONALITY;
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
Here is the code of unmarshalling
JAXBContext jaxbContext = JAXBContext.newInstance(ConsumerProfileDto.class);
StringReader reader = new StringReader(responseXML);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ConsumerDetailsDto que= (ConsumerDetailsDto) jaxbUnmarshaller.unmarshal(reader);
System.out.println(que.getDATE_OF_BIRTH());
System.out.println(que.getGENDER());;
System.out.println(que.getNAME());
P.S
I've used DocumentBuilder and I'm able to fetch the values using it. But, I want to extract using Jaxb.
You can't annotate as #XmlRootElement the Java class mirroring the XML element that you're interested on. You have to mirror in Java all the XML elements from the topmost element in the XML file (DATAPACKET) to the lowest ones (CONSUMER_DETAILS2 and ID_DETAILS2) in the path that you're interested, even if you're only interested in some of them.
I assume that the operator isn't interested in RUID (because the class CONSUMER_DETAILS2 doesn't include a field for this XML element), and also that the field NATIONALITY is not going to be loaded from this XML.
If the input XML of the question were in a file named input2.xml, then I'd have the following Java classes:
DataPacket
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "DATAPACKET")
public class DataPacket {
#XmlAttribute(name = "REQUEST_ID")
private int REQUEST_ID;
#XmlElement(name ="BODY")
private Body BODY;
public DataPacket(){}
public int getREQUEST_ID() {
return REQUEST_ID;
}
public void setREQUEST_ID(int REQUEST_ID) {
this.REQUEST_ID = REQUEST_ID;
}
public Body getBODY() {
return BODY;
}
public void setBODY(Body BODY) {
this.BODY = BODY;
}
}
Body
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class Body {
#XmlElement(name = "CONSUMER_PROFILE2")
private ConsumerProfile profile;
public Body(){}
public ConsumerProfile getProfile() {
return profile;
}
public void setProfile(ConsumerProfile profile) {
this.profile = profile;
}
}
ConsumerProfile
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
public class ConsumerProfile {
#XmlElement(name = "CONSUMER_DETAILS2")
private ConsumerDetails CONSUMER_DETAILS2;
#XmlElement(name = "ID_DETAILS2")
private IdDetails ID_DETAILS2;
public ConsumerProfile(){}
public ConsumerDetails getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetails cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetails getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetails iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
ConsumerDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class ConsumerDetails {
#XmlElement(name="NAME")
private String NAME;
#XmlElement(name="DATE_OF_BIRTH")
private String DATE_OF_BIRTH;
#XmlElement(name="GENDER")
private String GENDER;
private String NATIONALITY;
public ConsumerDetails(){}
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
}
IdDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class IdDetails {
#XmlElement(name="SLNO")
private int SLNO;
#XmlElement(name="SOURCE_ID")
private String SOURCE_ID;
#XmlElement(name="ID_VALUE")
private int ID_VALUE;
#XmlElement(name="EXP_DATE")
private String EXP_DATE;
public IdDetails(){}
public int getSLNO() {
return SLNO;
}
public void setSLNO(int SLNO) {
this.SLNO = SLNO;
}
public String getSOURCE_ID() {
return SOURCE_ID;
}
public void setSOURCE_ID(String SOURCE_ID) {
this.SOURCE_ID = SOURCE_ID;
}
public int getID_VALUE() {
return ID_VALUE;
}
public void setID_VALUE(int ID_VALUE) {
this.ID_VALUE = ID_VALUE;
}
public String getEXP_DATE() {
return EXP_DATE;
}
public void setEXP_DATE(String EXP_DATE) {
this.EXP_DATE = EXP_DATE;
}
}
Also, inside the same "test" package the jaxb.index file with:
DataPacket
ConsumerProfile
ConsumerDetails
IdDetails
Then, when testing with this Test class:
package test;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Test {
public static void main(String[] args) {
try{
JAXBContext jc = JAXBContext.newInstance(DataPacket.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input2.xml");
DataPacket dp = (DataPacket) unmarshaller.unmarshal(xml);
Body body = dp.getBODY();
ConsumerProfile profile = body.getProfile();
ConsumerDetails consumerDetail = profile.getCONSUMER_DETAILS2();
IdDetails idDetails = profile.getID_DETAILS2();
System.out.println("ConsumerDetails name:"+consumerDetail.getNAME()+
" date of birth:"+consumerDetail.getDATE_OF_BIRTH()+
" gender:"+consumerDetail.getGENDER()+
"IdDetails SLNO:"+idDetails.getSLNO()+
" SOURCE_ID:"+idDetails.getSOURCE_ID()+
" ID_VALUE:"+idDetails.getID_VALUE()+
" EXP_DATE:"+idDetails.getEXP_DATE());
}
catch(JAXBException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

Not able to unmarshall child object using jaxb [duplicate]

I've a very big XML string. Im posting here only part of the XML object. I'm trying to convert this XML to Java object. My first question is, should I need to create Java object of total XML tag values or can I have create the Java object of only selected inner XML objects? Please find my XML string.
<DATAPACKET REQUEST-ID = "2">
<HEADER>
<RESPONSE-TYPE CODE="1" DESCRIPTION="Response DataPacket"/>
<SEARCH-RESULT-LIST>
<SEARCH-RESULT-ITEM>
<NAME MATCHED="TRUE"/>
</SEARCH-RESULT-ITEM>
</SEARCH-RESULT-LIST>
</HEADER>
<BODY>
<CONS_SCORE>
<SCORE>0</SCORE>
<REASON1>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON1>
<REASON2>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON2>
<REASON3>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON3>
<REASON4>
<HEADER></HEADER>
<DESCRIPTION></DESCRIPTION>
</REASON4>
</CONS_SCORE>
<CONSUMER_PROFILE2>
<CONSUMER_DETAILS2>
<RUID>1234</RUID>
<NAME>ABC</NAME>
<DATE_OF_BIRTH>1980-03-03T00:00:00+03:00</DATE_OF_BIRTH>
<GENDER>001</GENDER>
</CONSUMER_DETAILS2>
<ID_DETAILS2>
<SLNO>1</SLNO>
<SOURCE_ID>001</SOURCE_ID>
<ID_VALUE>2806</ID_VALUE>
<EXP_DATE>2018-07-13T00:00:00+03:00</EXP_DATE>
</ID_DETAILS2>
</CONSUMER_PROFILE2>
</BODY>
</DATAPACKET>
In the above object, I want to fetch only CONSUMER_PROFILE2 object. Here is my Dto class
#XmlRootElement(name = "DATAPACKET")
public class ConsumerProfileDto {
private ConsumerDetailsDto CONSUMER_DETAILS2;
private IdDetailsDto ID_DETAILS2;
public ConsumerDetailsDto getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetailsDto cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetailsDto getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetailsDto iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
CONSUMER_DETAILS2 class
#XmlRootElement(name = "CONSUMER_DETAILS2")
public class ConsumerDetailsDto {
private String NAME;
private String DATE_OF_BIRTH;
private String GENDER;
private String NATIONALITY;
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
Here is the code of unmarshalling
JAXBContext jaxbContext = JAXBContext.newInstance(ConsumerProfileDto.class);
StringReader reader = new StringReader(responseXML);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ConsumerDetailsDto que= (ConsumerDetailsDto) jaxbUnmarshaller.unmarshal(reader);
System.out.println(que.getDATE_OF_BIRTH());
System.out.println(que.getGENDER());;
System.out.println(que.getNAME());
P.S
I've used DocumentBuilder and I'm able to fetch the values using it. But, I want to extract using Jaxb.
You can't annotate as #XmlRootElement the Java class mirroring the XML element that you're interested on. You have to mirror in Java all the XML elements from the topmost element in the XML file (DATAPACKET) to the lowest ones (CONSUMER_DETAILS2 and ID_DETAILS2) in the path that you're interested, even if you're only interested in some of them.
I assume that the operator isn't interested in RUID (because the class CONSUMER_DETAILS2 doesn't include a field for this XML element), and also that the field NATIONALITY is not going to be loaded from this XML.
If the input XML of the question were in a file named input2.xml, then I'd have the following Java classes:
DataPacket
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "DATAPACKET")
public class DataPacket {
#XmlAttribute(name = "REQUEST_ID")
private int REQUEST_ID;
#XmlElement(name ="BODY")
private Body BODY;
public DataPacket(){}
public int getREQUEST_ID() {
return REQUEST_ID;
}
public void setREQUEST_ID(int REQUEST_ID) {
this.REQUEST_ID = REQUEST_ID;
}
public Body getBODY() {
return BODY;
}
public void setBODY(Body BODY) {
this.BODY = BODY;
}
}
Body
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class Body {
#XmlElement(name = "CONSUMER_PROFILE2")
private ConsumerProfile profile;
public Body(){}
public ConsumerProfile getProfile() {
return profile;
}
public void setProfile(ConsumerProfile profile) {
this.profile = profile;
}
}
ConsumerProfile
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
public class ConsumerProfile {
#XmlElement(name = "CONSUMER_DETAILS2")
private ConsumerDetails CONSUMER_DETAILS2;
#XmlElement(name = "ID_DETAILS2")
private IdDetails ID_DETAILS2;
public ConsumerProfile(){}
public ConsumerDetails getCONSUMER_DETAILS2() {
return CONSUMER_DETAILS2;
}
public void setCONSUMER_DETAILS2(ConsumerDetails cONSUMER_DETAILS2) {
CONSUMER_DETAILS2 = cONSUMER_DETAILS2;
}
public IdDetails getID_DETAILS2() {
return ID_DETAILS2;
}
public void setID_DETAILS2(IdDetails iD_DETAILS2) {
ID_DETAILS2 = iD_DETAILS2;
}
}
ConsumerDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class ConsumerDetails {
#XmlElement(name="NAME")
private String NAME;
#XmlElement(name="DATE_OF_BIRTH")
private String DATE_OF_BIRTH;
#XmlElement(name="GENDER")
private String GENDER;
private String NATIONALITY;
public ConsumerDetails(){}
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getDATE_OF_BIRTH() {
return DATE_OF_BIRTH;
}
public void setDATE_OF_BIRTH(String dATE_OF_BIRTH) {
DATE_OF_BIRTH = dATE_OF_BIRTH;
}
public String getGENDER() {
return GENDER;
}
public void setGENDER(String gENDER) {
GENDER = gENDER;
}
public String getNATIONALITY() {
return NATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
NATIONALITY = nATIONALITY;
}
}
IdDetails
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
#XmlAccessorType(XmlAccessType.NONE)
class IdDetails {
#XmlElement(name="SLNO")
private int SLNO;
#XmlElement(name="SOURCE_ID")
private String SOURCE_ID;
#XmlElement(name="ID_VALUE")
private int ID_VALUE;
#XmlElement(name="EXP_DATE")
private String EXP_DATE;
public IdDetails(){}
public int getSLNO() {
return SLNO;
}
public void setSLNO(int SLNO) {
this.SLNO = SLNO;
}
public String getSOURCE_ID() {
return SOURCE_ID;
}
public void setSOURCE_ID(String SOURCE_ID) {
this.SOURCE_ID = SOURCE_ID;
}
public int getID_VALUE() {
return ID_VALUE;
}
public void setID_VALUE(int ID_VALUE) {
this.ID_VALUE = ID_VALUE;
}
public String getEXP_DATE() {
return EXP_DATE;
}
public void setEXP_DATE(String EXP_DATE) {
this.EXP_DATE = EXP_DATE;
}
}
Also, inside the same "test" package the jaxb.index file with:
DataPacket
ConsumerProfile
ConsumerDetails
IdDetails
Then, when testing with this Test class:
package test;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Test {
public static void main(String[] args) {
try{
JAXBContext jc = JAXBContext.newInstance(DataPacket.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input2.xml");
DataPacket dp = (DataPacket) unmarshaller.unmarshal(xml);
Body body = dp.getBODY();
ConsumerProfile profile = body.getProfile();
ConsumerDetails consumerDetail = profile.getCONSUMER_DETAILS2();
IdDetails idDetails = profile.getID_DETAILS2();
System.out.println("ConsumerDetails name:"+consumerDetail.getNAME()+
" date of birth:"+consumerDetail.getDATE_OF_BIRTH()+
" gender:"+consumerDetail.getGENDER()+
"IdDetails SLNO:"+idDetails.getSLNO()+
" SOURCE_ID:"+idDetails.getSOURCE_ID()+
" ID_VALUE:"+idDetails.getID_VALUE()+
" EXP_DATE:"+idDetails.getEXP_DATE());
}
catch(JAXBException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

Unable to get attribute value using JAXB ( For attribute in Parent class)

I am trying to read one xml using JAXB.
I am facing one weird issue where attribute of parent is not being read,but attributes of child classes are read.
I have referenced forums, but this seems to be a strange one.
Can anyone please let me know what is the mistake i am doing.
XML.
<?xml version="1.0" encoding="UTF-8"?>
<PhoneDirectory>
<Exchange exchangeName="ashfield2133">Ashfield</Exchange>
<PhoneNumber id="23" number="0489524401">
<FirstName>Test</FirstName>
<LastName>Test</LastName>
<Address>#34,rt road, State,Country,22344 </Address>
</PhoneNumber>
<PhoneNumber id="88" number="0409545401">
<FirstName>Testf2</FirstName>
<LastName>Testl2</LastName>
<Address>St 2 , State,Country,34555</Address>
</PhoneNumber>
<PhoneNumber id="88" number="0446775401">
<FirstName>Testf3</FirstName>
<LastName>Testl3</LastName>
<Address>St 3 , State,Country,546777</Address>
</PhoneNumber>
</PhoneDirectory>
PhoneDirectory Class
package com.test.phoneDirectory.dataclass;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
#XmlRootElement(name="PhoneDirectory")
public class PhoneDirectory {
private String exchange;
private String exchangeName;
#XmlElement(name="Exchange")
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
#XmlAttribute(name="exchangeName")
public String getExchangeName() {
return exchangeName;
}
public void setExchangeName(String exchangename) {
this.exchangeName = exchangename;
}
private List<PhoneNumber> phoneNumber;
#XmlElement(name="PhoneNumber")
public List<PhoneNumber> getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(List<PhoneNumber> phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
PhoneNumber Class
package com.test.phoneDirectory.dataclass;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="PhoneNumber")
public class PhoneNumber {
private String id;
private String number;
private String firstName;
private String lastName;
private String address;
#XmlAttribute(name="id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlAttribute(name="number")
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
#XmlElement(name="FirstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#XmlElement(name="LastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#XmlElement(name="Address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Main class
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.test.phoneDirectory.dataclass.PhoneDirectory;
import com.test.phoneDirectory.dataclass.PhoneNumber;
public class GetAllPhoneData {
public static void main(String[] args) throws JAXBException {
// TODO Auto-generated method stub
JAXBContext jc = JAXBContext.newInstance(PhoneDirectory.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
PhoneDirectory phoneDirectory = (PhoneDirectory) unmarshaller.unmarshal(new File("src/config/PhoneDirectory.xml"));
System.out.println("Get all phone details");
System.out.println("Exchange:"+phoneDirectory.getExchange());
System.out.println("exchangeName:"+phoneDirectory.getExchangeName());
for (PhoneNumber phonedetails : phoneDirectory.getPhoneNumber()) {
System.out.println(phonedetails.getId());
System.out.println(phonedetails.getNumber());
System.out.println(phonedetails.getFirstName());
System.out.println(phonedetails.getLastName());
System.out.println(phonedetails.getAddress());
}
}
}
Output
Get all phone details
Exchange: Ashfield
****Get exchangeName :null****
23
0489524401
Test
Test
#34,rt road, State,Country,22344
As you can see the exchangeName is null despite mentioning XMLAttribute annotation for field.
Thanks,
Vishnu
You've declared the exchangeName attribute in the PhoneDirectory class but your XML has this attribute in the Exchange element.
So instead of
private String exchange;
private String exchangeName;
you'll need a class like Exchange with #XmlAttribute exchangeName and #XmlValue exchange.

Reading XML files from java

I am trying to read an XML file from java program. I am able to read its contents.I am posting the XML file from which i am reading contents.
<?xml version="1.0" encoding="UTF-8" ?>
<customer id="100">
<age>29</age>
<name>lucifer</name>
</customer>
i am able to write its contents through java program i am posting my code..
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
public class CheckClass {
public static void main(String[] args) {
try {
File file = new File("./file/NewFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.age);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
But i have to read values from this XML file which i can not.This is my XML file
<?xml version="1.0" encoding="UTF-8"?>
<DBConfig ID="1" Name ="" DriverName="" HostName="localhost" PortName="" DBName="" ServiceName="" User="" PassWord="" sid="">
<TableConfig ID= "1" TableName="">
</TableConfig>
</DBConfig>
When i am trying to access this xml values through java class i am getting this error..
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "DBName"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getDBName()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.DBName
at com.gamma.DBConf
Class has two properties of the same name "sid"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getSid()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.sid
at com.gamma.DBConf
at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(Unknown Source)
at com.sun.xml.internal.bind.v2.ContextFactory.createContext(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at com.gamma.ReadXML.main(ReadXML.java:22)
and this is my java classes
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class DBConf {
public String Name;
public String DriverName;
public String HostName;
public String PortName;
public String DBName;
public String ServiceName;
public String User;
public String PassWord;
public String sid;
public String getName() {
return Name;
}
#XmlElement
public void setName(String name) {
Name = name;
}
public String getDriverName() {
return DriverName;
}
#XmlElement
public void setDriverName(String driverName) {
DriverName = driverName;
}
public String getHostName() {
return HostName;
}
#XmlElement
public void setHostName(String hostName) {
HostName = hostName;
}
public String getPortName() {
return PortName;
}
#XmlElement
public void setPortName(String portName) {
PortName = portName;
}
public String getDBName() {
return DBName;
}
#XmlElement
public void setDBName(String dBName) {
DBName = dBName;
}
public String getServiceName() {
return ServiceName;
}
#XmlElement
public void setServiceName(String serviceName) {
ServiceName = serviceName;
}
public String getUser() {
return User;
}
#XmlElement
public void setUser(String user) {
User = user;
}
public String getPassWord() {
return PassWord;
}
#XmlElement
public void setPassWord(String passWord) {
PassWord = passWord;
}
public String getSid() {
return sid;
}
#XmlElement
public void setSid(String sid) {
this.sid = sid;
}
}
And this is the main class
public class ReadXML {
/**
* #param args
*/
public static void main(String[] args) {
try {
File file = new File("./file/dbconfig.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DBConf.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
DBConf db = (DBConf) jaxbUnmarshaller.unmarshal(file);
System.out.println(db.HostName);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
can anyone help
Note that you are annotating Attribute as Element. Fix that.
Even after that if problem occurs -
Try using - #XmlAccessorType(XmlAccessType.FIELD)
Move #XmlAttribute(name = "HostName") annotations to fields instead of accessor methods.
I am not sure if this is your problem. I faced a similar problem and this helped me. I wont guarantee that it will solve your problem but prima facie, it appears that above can fix it.
dbName, sid are Attributes, but you have annotated them #XmlElement. change all the attributes to #XmlAttribute.
Why don't you use
Xstream library
Example:
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
#XStreamAlias("Cat")
class Cat {
#XStreamAsAttribute
int age;
String name;
}
public class XStreamDemo {
public static void main(String[] args) {
XStream xstream = new XStream();
xstream.processAnnotations(Cat.class);
String xml = "<Cat age='4' ><name>Garfield</name></Cat>";
Cat cat = (Cat) xstream.fromXML(xml);
System.out.println("name -> " + cat.name);
System.out.println("age -> " + cat.age);
}
}
You need to add Xstream jar files in to classpath.
Use these classes.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
#XmlRootElement(name = "TableConfig")
public class TableConfig {
#XmlValue
protected String value;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "TableName")
protected String tableName;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getTableName() {
return tableName;
}
public void setTableName(String value) {
this.tableName = value;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"tableConfig"
})
#XmlRootElement(name = "DBConfig")
public class DBConfig {
#XmlElement(name = "TableConfig", required = true)
protected TableConfig tableConfig;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "Name")
protected String name;
#XmlAttribute(name = "DriverName")
protected String driverName;
#XmlAttribute(name = "HostName")
protected String hostName;
#XmlAttribute(name = "PortName")
protected String portName;
#XmlAttribute(name = "DBName")
protected String dbName;
#XmlAttribute(name = "ServiceName")
protected String serviceName;
#XmlAttribute(name = "User")
protected String user;
#XmlAttribute(name = "PassWord")
protected String passWord;
#XmlAttribute
protected String sid;
public TableConfig getTableConfig() {
return tableConfig;
}
public void setTableConfig(TableConfig value) {
this.tableConfig = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getDriverName() {
return driverName;
}
public void setDriverName(String value) {
this.driverName = value;
}
public String getHostName() {
return hostName;
}
public void setHostName(String value) {
this.hostName = value;
}
public String getPortName() {
return portName;
}
public void setPortName(String value) {
this.portName = value;
}
public String getDBName() {
return dbName;
}
public void setDBName(String value) {
this.dbName = value;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String value) {
this.serviceName = value;
}
public String getUser() {
return user;
}
public void setUser(String value) {
this.user = value;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String value) {
this.passWord = value;
}
public String getSid() {
return sid;
}
public void setSid(String value) {
this.sid = value;
}
}

Categories