How to create XmlElement with no value with JAXB - java

Would like to create the following XML element using JAXB, no value(content), no closing element name, just closing '/' :
<ElementName attribute1="A" attribute2="B"" xsi:type="type" xmlns="some_namespace"/>
Trying the following
#XmlAccessorType(XmlAccessType.FIELD)
public class ElementName {
#XmlElement(name = "ElementName", nillable = true)
protected String value;
#XmlAttribute(name = "attribute1")
protected String attribute1;
#XmlAttribute(name = "attribute2")
protected String attribute2;
}
When constructing an object of this type as below, there is an exception
ElementName element = new ElementName();
What is the correct way of doing it ?

In case you want to achieve it for ElementName with value set to null remove nillable attribute. Simple example how to generate XML payload:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
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;
public class JaxbApp {
public static void main(String[] args) throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance(ElementName.class);
ElementName en = new ElementName();
en.attribute1 = "A";
en.attribute2 = "B";
en.value = null;
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(en, System.out);
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "ElementName")
class ElementName {
#XmlElement(name = "ElementName")
protected String value;
#XmlAttribute(name = "attribute1")
protected String attribute1;
#XmlAttribute(name = "attribute2")
protected String attribute2;
}
prints:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ElementName attribute1="A" attribute2="B"/>

Related

Read XML body element having multiple values based on different requests

I am parsing a XML request using Java. The XML structure is like this:
<?xml version="1.0" encoding="UTF-8"?>
<TestServices>
<header>
//Header Details
</header>
<body>
<ele1>
<ele2>
<ele3>534159XXXXXX0176</ele3> //Or ele_3, ele03, ele_03
</ele2>
</ele1>
</body>
</TestServices>
I have created classes for the same to read the Header and Body elements. Each node is a class and I am reading the ele3 value like this.
String ele3 = testServicesRequest.getBody().getEle1().getEle2().getEle3();
The element name for ele3 can be different based on different request. I have used Generate Java class from xsd feature in eclipse and it has generated classes like this.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"ele3"
})
public class ReqEle2 {
#XmlElement(name = "ele3", required = true)
protected String ele3;
public String getEle3() {
return ele3;
}
public void setEle3(String value) {
this.ele3 = value;
}
}
My requirement is simple. I just want to put multiple element names for single getEle3() method. eg. ele_3, ele03, ele_03 using less code changes. Or Please suggest me any other efficient way to do that.
For now I am trying to do this like this which I think is not good.
public class ReqEle3 {
#XmlElement(name = "ele03", required = true)
protected String ele3_1="";
#XmlElement(name = "ele_3", required = true)
protected String ele3_2="";
#XmlElement(name = "ele3", required = true)
protected String ele3_3="";
#XmlElement(name = "ele3_old", required = true)
protected String ele3_4="";
public String getEle3() {
if(ele3_1 != null && !ele3_1.isEmpty()){
return ele3_1;
}
else if(ele3_2 != null && !ele3_2.isEmpty()){
return ele3_2;
}
else if(ele3_3 != null && !ele3_3.isEmpty()){
return ele3_3;
}
else if(ele3_4 != null && !ele3_4.isEmpty()){
return ele3_4;
}
return "";
}
}
You can write custom deserialiser for ele3 node. To be precise, custom deserialiser for ele2 node because this is the last constant node. Below example contains only required part to understand the solution:
import org.w3c.dom.Element;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.io.StringReader;
public class JaxbApp {
public static void main(String[] args) throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance(ReqEle1.class);
String xml0 = "<ele1><ele2><ele3>534159XXXXXX0176</ele3></ele2></ele1>";
String xml1 = "<ele1><ele2><ele_3>534159XXXXXX0176</ele_3></ele2></ele1>";
String xml2 = "<ele1><ele2><ele03>534159XXXXXX0176</ele03></ele2></ele1>";
for (String xml : new String[]{xml0, xml1, xml2}) {
StringReader reader = new StringReader(xml);
Object unmarshal = jaxbContext.createUnmarshaller().unmarshal(reader);
System.out.println(unmarshal);
}
}
}
#XmlRootElement(name = "ele1")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {"ele2"})
class ReqEle1 {
#XmlJavaTypeAdapter(ReqEle2XmlAdapter.class)
#XmlElement(name = "ele2", required = true)
protected ReqEle2 ele2;
// getters, setters
}
class ReqEle2XmlAdapter extends XmlAdapter<Object, ReqEle2> {
#Override
public ReqEle2 unmarshal(Object v) {
Element element = (Element) v;
ReqEle2 reqEle2 = new ReqEle2();
reqEle2.setEle3(element.getFirstChild().getTextContent());
return reqEle2;
}
#Override
public Object marshal(ReqEle2 v) throws Exception {
return null; // Implement if needed
}
}
class ReqEle2 {
protected String ele3;
// getters, setters
}
Above code prints:
ReqEle1{ele2=ReqEle2{ele3='534159XXXXXX0176'}}
ReqEle1{ele2=ReqEle2{ele3='534159XXXXXX0176'}}
ReqEle1{ele2=ReqEle2{ele3='534159XXXXXX0176'}}
See also:
JAXB #XmlAdapter for arbitrary XML

Jaxb unmarshalls empty list with namespace [duplicate]

This question already has an answer here:
Issue with namespaces in XMLs in JAXB unmarshalling
(1 answer)
Closed 8 years ago.
I have a simple xml to unmarshall. But I get only an empty list in the output. No exceptions are thrown.
This is a third party generated xml and I need to make this work without any changes in the xml.
The XML:
<Animal xmlns="http://allmycats.com/serviceplatform/1.0/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Cat z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<name>kitty</name>
</Cat>
<Cat z:Id="i2" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<name>kitty2</name>
</Cat>
</Animal>
The POJO bean for Animal:
#XmlRootElement(name = "Animal",namespace = "http://allmycats.com/serviceplatform/1.0/")
public class Animal{
List<Cat> cats;
#XmlElement(name = "Cat")
public List<Cat> getCats() {
return cats;
}
public void setCats(List<Cat>cats) {
this.cats= cats;
}
}
The POJO bean for Cat
#XmlRootElement(name = "Cat")
public class Cat {
private String zId;
private String name;
#XmlAttribute(name = "Id", namespace="http://schemas.microsoft.com/2003/10/Serialization/")
public String getzId() {
return zId;
}
public void setzId(String zId) {
this.zId = zId;
}
#XmlElement(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The unmarshall code is:
File file = new File(filepath);
System.out.println("file exists? : "+ file.exists()); // prints true
JAXBContext jaxbContext = JAXBContext.newInstance(Animal2.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Animal2 animals = (Animal2)jaxbUnmarshaller.unmarshal( file );
System.out.println("--file size: "+animals.getCats().size());
The last line gives a null pointer exception.
Am I doing something wrong with the namespaces in the BEAN classes? I am new to Jaxb and this issue is bugging me for 3 days now !
I asked this question earlier but couldn't get proper answer and this is a more precise question.
Animal.java
import java.io.Serializable;
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;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "Animal",namespace = "http://allmycats.com/serviceplatform/1.0/")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Animal", propOrder = {
"cats"
})
public class Animal implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#XmlElement(name = "Cat")
protected List<Cat> cats;
public List<Cat> getCats() {
if (cats == null) { // This solve the nullpointer
cats = new ArrayList<Cat>();
}
return this.cats;
}
}
Cat.java
import java.io.Serializable;
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;
#XmlRootElement(name = "Cat")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Cat", propOrder = {
"name"
})
public class Cat implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#XmlAttribute(name = "Id", namespace="http://schemas.microsoft.com/2003/10/Serialization/")
private String zId;
#XmlElement(name = "name")
private String name;
public String getzId() {
return zId;
}
public void setzId(String zId) {
this.zId = zId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

There's no ObjectFactory with an #XmlElementDecl when there is static class

I am getting below exception, i need some help to resolve the issue.
If remove the namespace in the object factory and with out package-info.java class it is working fine.
Exception that is throwing now
Exception in thread "main" com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
There's no ObjectFactory with an #XmlElementDecl for the element {}shipping.
this problem is related to the following location:
at protected javax.xml.bind.JAXBElement com.jverstry.annotations.generics.Market$Detail.shipping
at com.jverstry.annotations.generics.Market$Detail
at protected com.jverstry.annotations.generics.Market$Detail com.jverstry.annotations.generics.Market.detail
at com.jverstry.annotations.generics.Market
ObjectFactory class which is creating the jaxbelement
package com.jverstry.annotations.generics;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import org.example.customer.Customer;
#XmlRegistry
public class ObjectFactory {
public ObjectFactory() {
}
public Market.Detail.Shipping createShipping() {
return new Market.Detail.Shipping();
}
private final static QName _Shipping_QNAME = new QName("http://www.example.org/customer", "shipping");
#XmlElementDecl(namespace = "http://www.example.org/customer", name = "shipping")
public JAXBElement<Market.Detail.Shipping> createShipping(Market.Detail.Shipping value) {
return new JAXBElement<Market.Detail.Shipping>(_Shipping_QNAME, Market.Detail.Shipping.class, value);
}
}
Class package-info.java, where the name spaces are mentioned for the response xml
#XmlSchema(namespace = "http://www.example.org/customer", elementFormDefault = XmlNsForm.QUALIFIED)
package com.jverstry.annotations.generics;
import javax.xml.bind.annotation.*;
Demo class where marshalling object
package com.jverstry.annotations.generics;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Market.class);
Market market = new Market();
Market.Detail md = new Market.Detail();
Market.Detail.Shipping mds = new Market.Detail.Shipping();
mds.setAvailable(false);
JAXBElement<Market.Detail.Shipping> shipping = new ObjectFactory().createShipping(mds);
shipping.setNil(true);
md.setShipping(shipping);
market.setDetail(md);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(market, System.out);
}
}
Market class, this is the main root class where jaxbcontext is created
package com.jverstry.annotations.generics;
import java.math.BigDecimal;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "detail" })
#XmlRootElement(name = "Market")
public class Market
{
#XmlElement(required = false)
protected Market.Detail detail;
public Market.Detail getDetail() {
return detail;
}
public void setDetail(Market.Detail detail) {
this.detail = detail;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "shipping" })
public static class Detail
{
#XmlElementRef(name = "shipping")
protected JAXBElement<Market.Detail.Shipping> shipping;
public JAXBElement<Market.Detail.Shipping> getShipping() {
return shipping;
}
public void setShipping(JAXBElement<Market.Detail.Shipping> value) {
this.shipping = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "value" })
public static class Shipping
{
#XmlValue
protected BigDecimal value;
#XmlAttribute(name = "available")
protected Boolean available;
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
public Boolean getAvailable() {
return available;
}
public void setAvailable(Boolean value) {
this.available = value;
}
}
}
}
You need to create the JAXBContext by passing in the ObjectFactory class or the package name of the generated model to ensure the ObjectFactory class is processed.
If you specify the namespace property on the #XmlElementRef annotation things should work.

jaxb unmarshall child #XmlIDREF

I have class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "customerOrder", propOrder = {
"demandsUuid",
"invoicesOutUuid",
"paymentsUuid",
"customerOrderPosition",
"purchaseOrdersUuid"
})
public class CustomerOrder extends LegendEntity {
#XmlAttribute(name = "sourceAgentUuid")
#XmlIDREF
#XmlSchemaType(name = "IDREF")
#XmlJavaTypeAdapter(XmlAdapterTest.class)
protected Object sourceAgentUuid;
....
Also Agent class for sourceAgentUuid field
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "agent", propOrder = {
"attribute",
"requisite",
"contact",
"contactPerson",
"agentNewsItem",
"tags"
})
#XmlSeeAlso({
Company.class
})
public class Agent
extends LegendEntity
{
#XmlJavaTypeAdapter(CollapsedStringAdapter.class)
#XmlID
#XmlSchemaType(name = "ID")
protected String uuid;
And unmarshalling xml snipetpets
<?xml version="1.0" encoding="UTF-8"?>
<customerOrder deliveryPlannedMoment="2014-04-23T16:10:00+04:00" reservedSum="0.0" stateUuid="44b3fca5-a2b3-11e3-31b2-002590a28eca" targetAgentUuid="9a3c7d6b-4245-11e3-24c6-7054d21a8d1e"
sourceAgentUuid="ef0b03de-c95b-11e3-9183-002590a28eca" sourceStoreUuid="b05ed064-8743-11e3-0c1a-002590a28eca"
applicable="true" moment="2014-04-21T17:50:00+04:00" payerVat="true" rate="1.0" vatIncluded="true" created="2014-04-21T17:50:44.142+04:00" createdBy="it#erms" name="440" updated="2014-04-22T12:19:56.472+04:00" updatedBy="it#erms" readMode="SELF" changeMode="NONE">
<accountUuid>5f65cc9e-3708-11e3-bf9a-7054d21a8d1e</accountUuid>
<accountId>5f65cc9e-3708-11e3-bf9a-7054d21a8d1e</accountId>
<uuid>ef1267b8-c95b-11e3-aeb4-002590a28eca</uuid>
<groupUuid>9a3ad96b-4245-11e3-010e-7054d21a8d1e</groupUuid>
<groupId>9a3ad96b-4245-11e3-010e-7054d21a8d1e</groupId>
<code>440</code>
<externalcode>440</externalcode>
When I try to unmarshall
JAXBElement poe = (JAXBElement)u.unmarshal( new FileInputStream( "org_order.xml" ) );
CustomerOrder co=(CustomerOrder)poe.getValue();
System.out.println(co.getSourceAgentUuid());
result null (but all other not #XmlIDREF field unmarshalled ok)
How I can get ef0b03de-c95b-11e3-9183-002590a28eca result ?
I had create test class for simply.
Why output is null?
import java.io.ByteArrayInputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class TestMarshall {
public static void main(String[] args) {
try {
// marshal();
unmarshal();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void marshal() throws Exception {
CustomerOrder co = new CustomerOrder();
Agent a = new Agent();
a.setUuid("sdfsdf");
co.setSourceAgentUuid(a);
JAXBContext jc = JAXBContext.newInstance(CustomerOrder.class,
Agent.class);
Marshaller m = jc.createMarshaller();
m.marshal(co, System.out);
}
public static void unmarshal() throws Exception {
JAXBContext jc = JAXBContext.newInstance(CustomerOrder.class,
Agent.class);
Unmarshaller u = jc.createUnmarshaller();
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><customerOrder sourceAgentUuid=\"sdfsdf\"/>";
CustomerOrder poe = (CustomerOrder) u
.unmarshal(new ByteArrayInputStream(testXML.getBytes()));
CustomerOrder co = poe;
System.out.println("sourceAgentUuid= " + co.getSourceAgentUuid());
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "agent")
class Agent {
#XmlJavaTypeAdapter(CollapsedStringAdapter.class)
#XmlID
#XmlSchemaType(name = "ID")
protected String uuid;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
#XmlType(name = "customerOrder")
class CustomerOrder {
#XmlAttribute(name = "sourceAgentUuid")
#XmlIDREF
#XmlSchemaType(name = "IDREF")
protected Object sourceAgentUuid;
public Object getSourceAgentUuid() {
return sourceAgentUuid;
}
public void setSourceAgentUuid(Object sourceAgentUuid) {
this.sourceAgentUuid = sourceAgentUuid;
}
}
An #XmlIDREF plus its counterpart #XmlID are "XMLized pointers" that appear as strings in the XML text. JAXB matches such value pairs and resolves matching references into nice object references.
So, after unmarshalling, you won't see the strings from the XML file; the
Object sourceAgentUuid
(in your case) will either contain a reference to that "source agent" object (if there is such an XML element with its #XmlID set to that value) or null otherwise.

JAXB unmarshal XML elements to HashMap

I found a lot of articles that describe how to unmarshal a sequence of XML elements to a HashMap as long as they are within a "parent" element. However, I do not get this to work with the children directly under the root element!
Option 1 - Works:
<?xml version="1.0" encoding="UTF-8"?>
<checks>
<checks>
<check key="check1"/>
<check key="check2"/>
...
</checks>
</checks>
Option 2 - Does not work:
<?xml version="1.0" encoding="UTF-8"?>
<checks>
<check key="check1"/>
<check key="check2"/>
...
</checks>
Checks:
package com.foo.conf;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement(name="checks")
public class Checks {
#XmlJavaTypeAdapter(ChecksAdapter.class)
#XmlElement(name="checks")
public Map<String, Check> checkMap;
}
Check:
package com.foo.conf;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
public class Check {
#XmlAttribute public String key;
#XmlValue public String description;
public Check() { }
public Check(String key) {
this.key = key;
}
public String getCheckKey() {
return this.key;
}
}
CheckMapType:
package com.foo.conf;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
class CheckMapType {
#XmlElement(name="check")
public List<Check> checkList; // = new ArrayList<Check>();
}
ChecksAdapter:
package com.foo.conf;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.adapters.XmlAdapter;
final class ChecksAdapter extends XmlAdapter<CheckMapType, Map<String, Check>> {
#Override
public CheckMapType marshal(Map<String, Check> arg0) throws Exception {
return null;
}
#Override
public Map<String, Check> unmarshal(CheckMapType arg0) throws Exception {
System.out.println("u: " + arg0.checkList.size());
Map<String, Check> map = new HashMap<String, Check>();
for (Check check : arg0.checkList) {
System.out.println(check);
map.put(check.key, check);
}
return map;
}
}
This is (some dummy test lineS) how I generate the classes/invoke the unmarshalling:
JAXBContext jc = JAXBContext.newInstance(Checks.class);
Unmarshaller u = jc.createUnmarshaller();
Checks c = (Checks) u.unmarshal(new File("checks.xml"));
System.out.println(c.checkMap.size());
Any idea on how to get option #2 to work? It works when using a List instead of the Map but I need the HashMap as I have to access the objects by the given keys...
Any hints much appreciated!
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
JAXB will treat each object relationship with a nesting relationship. Map is treated like an Object instead of a Collection so this is why you are getting the behaviour that you are seeing.
MOXy has an XPath based mapping extension called #XmlPath that could be used for this use case.
package com.foo.conf;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name="checks")
public class Checks {
#XmlJavaTypeAdapter(ChecksAdapter.class)
#XmlPath(".")
public Map<String, Check> checkMap;
}
For More Information
http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
How are you generaing the JAXB classes? I am not sure what exactly are you trying to do but the below very simple code works for me ..
JAXBContext jc = JAXBContext.newInstance(ChecksType.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
ChecksType chksType = (ChecksType) unmarshaller.unmarshal(new File("/path/to/xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(chksType, System.out);
System.err.println(chksType.getCheck().get(0).getKey());
for (CheckType checkType : chksType.getCheck()) {
System.out.println("key = " + checkType.getKey() + ", " + checkType);
}
and here is my JAXB generated classes ..
ChecksType (Root element)
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "checksType", propOrder = { "check" })
#XmlRootElement(name = "checks")
public class ChecksType {
#XmlElement(required = true)
protected List<CheckType> check;
public List<CheckType> getCheck() {
if (check == null) {
check = new ArrayList<CheckType>();
}
return this.check;
}
}
And checkType (the child)
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "checkType")
public class CheckType {
#XmlAttribute(name = "key")
protected String key;
public String getKey() {
return key;
}
public void setKey(String value) {
this.key = value;
}
}

Categories