Parsing XML data into string objects using JAXB - java

I have to parse a xml into string objects in JAXB. But how to creates objects for this xml
Country.xml
<?xml version="1.0" encoding="UTF-8"?>
<Country>
<name>India</name>
<capital>New Delhi</capital>
<population>120crores</population>
.
.
.
.
.
<states>
<state>
<name>Maharastra</name>
<pincode>xyzzzz</pincode>
<capital>Mumbai</capital>
<\state>
<state>
.
.
.
</state>
</states>
<\Country>
And to parse this xml I have created class to map the objects which creates the objects and print it in the console. But Don't know what I am doing wrong.
#XmlElementWrapper(name="Country")
public void setCountry(String Countryv) {
Country= Countryv;
}
#XmlElement (name = "name")
public void setname(String namev) {
name= namev;
}
#XmlElement (name = "capital")
public void setcapital(String capitalv) {
capital= capitalv;
}
#XmlElement (name = "population")
public void setpopulation(String populationv) {
population= populationv;
}
#XmlElementWrapper(name="states")
public void setType(String statesv) {
states = statesv;
}
#XmlElementWrapper(name="state")
public void setType(String statev) {
state = statev;
}
#XmlElement (name = "name")
public void setpopulation(String namev) {
name= namev;
}
#XmlElement (name = "pincode")
public void setpopulation(String pincodev) {
pincode= pincodev;
}
#XmlElement (name = "capital")
public void setpopulation(String capitalv) {
capital= capitalv;
}
when I run the program I m getting the
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
counts of IllegalAnnotationExceptions
How to add wrapper anotations to wrapping the elements under separate headers and headers inside other headers.

Try this class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"capital",
"population",
"states"
})
#XmlRootElement(name = "Country")
public class Country {
#XmlElement(required = true)
protected String name;
#XmlElement(required = true)
protected String capital;
#XmlElement(required = true)
protected String population;
#XmlElement(required = true)
protected Country.States states;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getCapital() {
return capital;
}
public void setCapital(String value) {
this.capital = value;
}
public String getPopulation() {
return population;
}
public void setPopulation(String value) {
this.population = value;
}
public Country.States getStates() {
return states;
}
public void setStates(Country.States value) {
this.states = value;
}

This worked for me
class Country {
#XmlElement
String name;
//...
#XmlElementWrapper(name="states")
List<State> state;
}
class State {
#XmlElement
String name;
//..
}

Related

How do I reference a JAXB POJO in a mule flow

I have successfully unmarshalled an XML document into a JAXB object but now, I would like to reference the object in the flow and insert the value of it's properties into a database table.
The flow is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="10009" basePath="/ipay/bra" doc:name="HTTP Listener Configuration"/>
<mulexml:jaxb-context name="JAXB_Context" packageNames="com.dhg.api" doc:name="JAXB Context"/>
<flow name="transaction_initiation_testFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/transaction" doc:name="HTTP">
<http:response-builder>
<http:header headerName="Content-Type" value="text/xml"/>
</http:response-builder>
</http:listener>
<mulexml:jaxb-xml-to-object-transformer returnClass="com.dhg.api.PAYMENTS" jaxbContext-ref="JAXB_Context" doc:name="XML to JAXB Object"/>
<logger message="#[payload.transaction.email]" level="INFO" doc:name="Logger"/>
<echo-component doc:name="Echo"/>
</flow>
</mule>
The object is as follows:
package com.dhg.api;
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.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {"transaction"})
#XmlRootElement(name = "PAYMENTS")
public class PAYMENTS {
#XmlElement(name = "TRANSACTION", required = true)
protected PAYMENTS.TRANSACTION transaction;
public PAYMENTS.TRANSACTION getTRANSACTION() {
return transaction;
}
public void setTRANSACTION(PAYMENTS.TRANSACTION value) {
this.transaction = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"entity",
"useraddress1",
"useraddress2",
"useraddress3",
"usercountry",
"userparish",
"totalamount",
"payer",
"status",
"ipaynumber",
"email"
})
public static class TRANSACTION {
#XmlElement(name = "ENTITY", required = true)
protected PAYMENTS.TRANSACTION.ENTITY entity;
#XmlElement(name = "USERADDRESS1", required = true)
protected String useraddress1;
#XmlElement(name = "USERADDRESS2", required = true)
protected String useraddress2;
#XmlElement(name = "USERADDRESS3", required = true)
protected String useraddress3;
#XmlElement(name = "USERCOUNTRY", required = true)
protected String usercountry;
#XmlElement(name = "USERPARISH", required = true)
protected String userparish;
#XmlElement(name = "TOTALAMOUNT")
protected float totalamount;
#XmlElement(name = "PAYER", required = true)
protected String payer;
#XmlElement(name = "STATUS", required = true)
protected String status;
#XmlElement(name = "IPAYNUMBER")
protected int ipaynumber;
#XmlElement(name = "EMAIL", required = true)
protected String email;
#XmlAttribute(name = "txdate")
protected String txdate;
#XmlAttribute(name = "txno")
protected String txno;
public PAYMENTS.TRANSACTION.ENTITY getENTITY() {
return entity;
}
public void setENTITY(PAYMENTS.TRANSACTION.ENTITY value) {
this.entity = value;
}
public String getUSERADDRESS1() {
return useraddress1;
}
public void setUSERADDRESS1(String value) {
this.useraddress1 = value;
}
public String getUSERADDRESS2() {
return useraddress2;
}
public void setUSERADDRESS2(String value) {
this.useraddress2 = value;
}
public String getUSERADDRESS3() {
return useraddress3;
}
public void setUSERADDRESS3(String value) {
this.useraddress3 = value;
}
public String getUSERCOUNTRY() {
return usercountry;
}
public void setUSERCOUNTRY(String value) {
this.usercountry = value;
}
public String getUSERPARISH() {
return userparish;
}
public void setUSERPARISH(String value) {
this.userparish = value;
}
public float getTOTALAMOUNT() {
return totalamount;
}
public void setTOTALAMOUNT(float value) {
this.totalamount = value;
}
public String getPAYER() {
return payer;
}
public void setPAYER(String value) {
this.payer = value;
}
public String getSTATUS() {
return status;
}
public void setSTATUS(String value) {
this.status = value;
}
public int getIPAYNUMBER() {
return ipaynumber;
}
public void setIPAYNUMBER(int value) {
this.ipaynumber = value;
}
public String getEMAIL() {
return email;
}
public void setEMAIL(String value) {
this.email = value;
}
public String getTxdate() {
return txdate;
}
public void setTxdate(String value) {
this.txdate = value;
}
public String getTxno() {
return txno;
}
public void setTxno(String value) {
this.txno = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"account"
})
public static class ENTITY {
#XmlElement(name = "ACCOUNT", required = true)
protected PAYMENTS.TRANSACTION.ENTITY.ACCOUNT account;
#XmlAttribute(name = "biller")
protected String biller;
public PAYMENTS.TRANSACTION.ENTITY.ACCOUNT getACCOUNT() {
return account;
}
public void setACCOUNT(PAYMENTS.TRANSACTION.ENTITY.ACCOUNT value) {
this.account = value;
}
public String getBiller() {
return biller;
}
public void setBiller(String value) {
this.biller = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"details"
})
public static class ACCOUNT {
#XmlElement(name = "DETAILS", required = true)
protected PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS details;
#XmlAttribute(name = "bpnumber")
protected Integer bpnumber;
public PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS getDETAILS(){
return details;
}
public void setDETAILS(PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS value) {
this.details = value;
}
public Integer getBpnumber() {
return bpnumber;
}
public void setBpnumber(Integer value) {
this.bpnumber = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"dockey"
})
public static class DETAILS {
#XmlElement(name = "DOCKEY")
protected List<PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS.DOCKEY> dockey;
public List<PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS.DOCKEY> getDOCKEY() {
if (dockey == null) {
dockey = new ArrayList<PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS.DOCKEY>();
}
return this.dockey;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
public static class DOCKEY {
#XmlValue
protected String value;
#XmlAttribute(name = "payment")
protected Float payment;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Float getPayment() {
return payment;
}
public void setPayment(Float value) {
this.payment = value;
}
}
}
}
}
}
}
After unmarshalling, the object is instantiated as com.dhg.api.PAYMENTS#some_random_string, which makes it difficult to reference. So my question is simply, how can I refer to this object and be able to access the values for use elsewhere in the flow.
Thanks for your help.
Your setter/getter is not compliant with property names in :
public PAYMENTS.TRANSACTION getTRANSACTION() {
return transaction;
}
public void setTRANSACTION(PAYMENTS.TRANSACTION value) {
this.transaction = value;
}
So in <logger message="#[payload.transaction.email]" level="INFO" doc:name="Logger"/> the transaction part is null.
The correct getter name is getTransaction and is the same for setter. Change them please

Stop converting < to &lt, > to &gt and & to & in spring controller response

I am trying to generate a small xml. This xml should have a CDATA in it. Now the problem is I managed to generate CDATA, but the xml that is generated have < and > and &
I am using spring-mvc. I am interested in getting the right xml with CDATA in it.
Sample xml is as follow :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Customer>
<Active>1</Active>
<AlertMessage></AlertMessage>
<Currency>GBP</Currency>
<CustomerNumber>123</CustomerNumber>
<Forename>AD</Forename>
<balancetoallow>
<balance saving="10" spend="9990" type="2">
<value>\<![CDATA[$100 off on two purchase of jeans XYZ Brand.]]\></value>
</balance>
</balancetoallow>
<Surname>CD</Surname>
</Customer>
I have also overridden one of the converter as follow.
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
P.S I am using spring rest controller for my web service.
Here is the model class :
public class Balance{
private String value;
private String type;
private String saving;
private String spend;
public String getValue() {
return value;
}
#XmlJavaTypeAdapter(AdapterCDATA.class)
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
#XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getSaving() {
return saving;
}
#XmlAttribute
public void setSaving(String saving) {
this.saving = saving;
}
public String getSpend() {
return spend;
}
#XmlAttribute
public void setSpend(String spend) {
this.spend = spend;
}
}
This class is again part of another class.
public class Balancetoallows {
private List<Balance> balancetoallow ;
public List<Balance> getBalancetoallow () {
return balancetoallow;
}
#XmlElement(name="balancetoallow ")
public void setBalancetoallow (List<Balance > balancetoallow ) {
this.balancetoallow= balancetoallow;
}
}
And this is part of this class.
The parent class.
#XmlRootElement(name = "Customer")
public class Customer {
private String surname ;
private String forename;
private BalanceToAllow balanceToAllow;
private final String active="1";
private final String currency = "GBP";
private final String alertMessage="";
public String getCustomerNumber() {
return customerNumber;
}
#XmlElement(name="CustomerNumber")
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
#XmlElement(name="Active")
public String getActive() {
return active;
}
#XmlElement(name="Currency")
public String getCurrency() {
return currency;
}
public String getSurname() {
return surname;
}
#XmlElement(name="Surname")
public void setSurname(String surname) {
this.surname = surname;
}
public String getForename() {
return forename;
}
#XmlElement(name="Forename")
public void setForename(String forename) {
this.forename = forename;
}
#XmlElement(name="AlertMessage")
public String getAlertMessage() {
return alertMessage;
}
public BalanceToAllow getBalanceToAllow() {
return BalanceToAllow;
}
#XmlElement(name="balanceToAllow")
public void setFuturePromotions(BalanceToAllow balanceToAllow) {
this.balanceToAllow= balanceToAllow;
}
}
Thanks for reading.

Adding attribute to xml element within JAXB API

I am using JAXB API for mapping a Java object to XML. My Java class is
#XmlRootElement(name = "ad")
#XmlAccessorType(XmlAccessType.FIELD)
class Item {
#XmlElement(name = "id", nillable = false)
#XmlCDATA
private int id;
#XmlElement(name = "url", nillable = false)
#XmlCDATA
private String url;
public Item() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Output is like this :
<ad>
<id><![CDATA[ 104 ]]></id>
<url><![CDATA[www.google.com]]></url>
</ad>
I need to add an attribute to url element, for example :
<ad>
<id><![CDATA[ 104 ]]></id>
<url type="fr"><![CDATA[www.google.fr]]></url>
</ad>
I have tried many combinaisons using #XmlValue and #XmlAttribute ...
Your url variable should not be a String, but should be its own type. You should create a separate class for the url item, Url, and give it a String field, type, with an #XmlAttribute annotation.
For example,
#XmlRootElement(name = "ad")
#XmlAccessorType(XmlAccessType.FIELD)
class Item {
#XmlElement(name = "id")
private int id;
#XmlElement(name = "url")
private Url url;
public Item() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
// #XmlAttribute
public Url getUrl() {
return url;
}
public void setUrl(Url url) {
this.url = url;
}
}
#XmlRootElement(name = "url")
#XmlAccessorType(XmlAccessType.FIELD)
class Url {
#XmlValue
private String value;
#XmlAttribute(name = "type")
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Note that I don't have MOXY so I can't use or test your #XmlCDATA annotation.

Want to create a hashmap with a key(String) and value(Node)

I want to create a hashmap which is to have as 'Key' and the node as 'Value'. Can i know how do i do that using hashmap ? I will be creating two hashmaps on similar pattern, later want to compare it based on the 'Key(srv_field). Let me know how do i initialise and store the required data into hashmap.
Input xml is as below.
<?xml version="1.0" encoding="UTF-8"?>
<menu-details>
<menu name="HCOTA">
<group name="cota" type="M">
<page-details>
<page>
<name>cotacrit</name>
<field>
<field-type></field-type>
<srv-field>taChrgOffMsg.taChrgOffCrit.funcCode</srv-field>
<ui-field>funcCode</ui-field>
<label>FLT000204</label>
<mandatory>Y</mandatory>
<custom-pattern type=""></custom-pattern>
</field>
<field >
<field-type></field-type>
<srv-field>taChrgOffMsg.taChrgOffCrit.Acct.foracid</srv-field>
<ui-field>acctId</ui-field>
<label>FLT000265</label>
<mandatory>Y</mandatory>
<custom-pattern type=""></custom-pattern>
</field>
<field>
<srv-field>taChrgOffMsg.taChrgOffCrit.chargeOffType</srv-field>
<ui-field>chargeOffMode</ui-field>
<label>FLT004530</label>
<mandatory>Y</mandatory>
</field>
</page>
</page-details>
</group>
</menu>
</menu-details>
Java Object :
package com.ui.mig.menuvo;
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.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"menu"
})
#XmlRootElement(name = "menu-details")
public class MenuDetails {
protected List<MenuDetails.Menu> menu;
public List<MenuDetails.Menu> getMenu() {
if (menu == null) {
menu = new ArrayList<MenuDetails.Menu>();
}
return this.menu;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"group"
})
public static class Menu {
protected List<MenuDetails.Menu.Group> group;
#XmlAttribute(name = "name", namespace = "http://www..com/migration/")
protected String name;
public List<MenuDetails.Menu.Group> getGroup() {
if (group == null) {
group = new ArrayList<MenuDetails.Menu.Group>();
}
return this.group;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"pageDetails"
})
public static class Group {
#XmlElement(name = "page-details", required = true)
protected MenuDetails.Menu.Group.PageDetails pageDetails;
#XmlAttribute(name = "name", namespace = "http://www..com/migration/")
protected String name;
#XmlAttribute(name = "type", namespace = "http://www./migration/")
protected String type;
public MenuDetails.Menu.Group.PageDetails getPageDetails() {
return pageDetails;
}
public void setPageDetails(MenuDetails.Menu.Group.PageDetails value) {
this.pageDetails = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"page"
})
public static class PageDetails {
protected List<MenuDetails.Menu.Group.PageDetails.Page> page;
public List<MenuDetails.Menu.Group.PageDetails.Page> getPage() {
if (page == null) {
page = new ArrayList<MenuDetails.Menu.Group.PageDetails.Page>();
}
return this.page;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"pageName",
"field"
})
public static class Page {
#XmlElement(name = "page-name", required = true)
protected String pageName;
protected List<MenuDetails.Menu.Group.PageDetails.Page.Field> field;
public String getPageName() {
return pageName;
}
public void setPageName(String value) {
this.pageName = value;
}
public List<MenuDetails.Menu.Group.PageDetails.Page.Field> getField() {
if (field == null) {
field = new ArrayList<MenuDetails.Menu.Group.PageDetails.Page.Field>();
}
return this.field;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"fieldType",
"srvField",
"uiField",
"label",
"mandatory",
"customPattern"
})
public static class Field {
#XmlElement(name = "field-type", required = true)
protected String fieldType;
#XmlElement(name = "srv-field", required = true)
protected String srvField;
#XmlElement(name = "ui-field", required = true)
protected String uiField;
#XmlElement(required = true)
protected String label;
#XmlElement(required = true)
protected String mandatory;
#XmlElement(name = "custom-pattern", required = true)
protected MenuDetails.Menu.Group.PageDetails.Page.Field.CustomPattern customPattern;
public String getFieldType() {
return fieldType;
}
public void setFieldType(String value) {
this.fieldType = value;
}
public String getSrvField() {
return srvField;
}
public void setSrvField(String value) {
this.srvField = value;
}
public String getUiField() {
return uiField;
}
public void setUiField(String value) {
this.uiField = value;
}
public String getLabel() {
return label;
}
public void setLabel(String value) {
this.label = value;
}
public String getMandatory() {
return mandatory;
}
public void setMandatory(String value) {
this.mandatory = value;
}
public MenuDetails.Menu.Group.PageDetails.Page.Field.CustomPattern getCustomPattern() {
return customPattern;
}
public void setCustomPattern(MenuDetails.Menu.Group.PageDetails.Page.Field.CustomPattern value) {
this.customPattern = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
public static class CustomPattern {
#XmlValue
protected String value;
#XmlAttribute(name = "type", namespace = "http://www.com/migration/")
protected String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
}
}
}
}
}
}
}
Map<String,Node> map = new HashMap<String,Node>();
// or new HashMap<>();
map.put("asdf", new Node());
To get a value:
Node n = map.get("asdf");
You can compare values by getting Nodes from two Maps and comparing them, possibly with .equals().
There are other Map methods, which are detailed in the documentation.

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