Unmarshall XML element that occurs more than once using JAXB - java

I am trying to unmarshal XML document into my model. The issue is that I have one XML element <additional_detail> that occurs more than once in the XML document. When I unmarshal the XML document, the JSON element has the value of the last occurrence of <additional_detail>. What I am trying to achieve is having them all comma-separated maybe.
Exampple of document
.
.
.
<additional_detail>
160cm
</additional_detail>
<additional_detail>
200KG
</additional_detail>
.
.
.
and I have in my java model:
#XmlElement(name = "additional_detail", namespace = NAME_SPACE)
private String additionalDetail;

hopefully below example can help
xml
<Example>
<detail>1</detail>
<detail>2</detail>
<detail>3</detail>
</Example>
code
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public class JaxBUnmarshalExample {
public static void main(String[] args) {
try {
File file = new File("file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Example.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Example que = (Example) jaxbUnmarshaller.unmarshal(file);
System.out.println(que.details);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
#XmlRootElement(name = "Example")
class Example {
List<String> details = new ArrayList<String>();
String detail;
#XmlElement(name = "detail")
public String getDetail() {
return detail;
}
/*
here adding items in list later list can be used
*/
public void setDetail(String detail) {
details.add(detail);
this.detail = detail;
}
}

As mentioned in the comment you should use the List to capture all the information which have the same tags in XML. Following is the example which shows the example of the similar xml:
XML:
<root>
<additional_detail>160cm</additional_detail>
<additional_detail>200KG</additional_detail>
</root>
Parent.class:
#XmlRootElement(name = "root")
#Data
#XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
#XmlElement(name = "additional_detail")
List<String> additional_detail;
}
Main.class:
public class Main {
public static void main(String[] args) throws JAXBException, XMLStreamException {
final InputStream inputStream = Main.class.getClassLoader().getResourceAsStream("action.xml");
final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
final Unmarshaller unmarshaller = JAXBContext.newInstance(Parent.class).createUnmarshaller();
final Parent parent = unmarshaller.unmarshal(xmlStreamReader, Parent.class).getValue();
System.out.println(parent.toString());
Marshaller marshaller = JAXBContext.newInstance(Parent.class).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(parent, System.out);
}
}
If in case you have the outer tags for those lists something like additional_details (observe the 's') then you can do something like this:
<root>
<additional_details>
<additional_detail>160cm</additional_detail>
<additional_detail>200KG</additional_detail>
</additional_details>
</root>
Parent.class:
#XmlRootElement(name = "root")
#Data
#XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
#XmlElementWrapper(name = "additional_details")
#XmlElement(name = "additional_detail")
List<String> additional_detail;
}

Related

Unmarshalling a simple XML

I am having hard time unmarshalling the following XML using JAXB. This is the xml which is having only one field with an attribute. I have referred many tutorials where they only do an example of reading a string in fields which s not helpful in my case.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CircuitImpactConfigs id="1">
<Objects>
<Object type="1" impactAnalysisDataBuilderClassName="tttttttt"/>
<Object type="2" impactAnalysisDataBuilderClassName="yyyyyyyyy"/>
<Object type="3" impactAnalysisDataBuilderClassName="eeeeeee" />
<Object type="4" impactAnalysisDataBuilderClassName="iiiiiiiii"/>
<Object type="5" impactAnalysisDataBuilderClassName="rrrrrrrrrr"/>
<Object type="6" impactAnalysisDataBuilderClassName="zzzzzz"/>
<Object type="7" impactAnalysisDataBuilderClassName="qqqqqqqqqqq"/>
</Objects>
<ForceSwitchMode name="FORCE_SWITCHED" />
</CircuitImpactConfigs>
Based on what i learnt from tutorial
My Classes are CircuitImpactConfigs.java
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlRootElement(name = "CircuitImpactConfigs")
#XmlAccessorType(XmlAccessType.FIELD)
public class CircuitImpactConfigs {
private ForceSwitchMode ForceSwitchMode;
List<Obj> Object;
#XmlElement
public List<Obj> getObject() {
return Object;
}
public void setObject(List<Obj> object) {
Object = object;
}
#XmlElement
public ForceSwitchMode getForceSwitchMode() {
return ForceSwitchMode;
}
public void setForceSwitchMode(ForceSwitchMode forceSwitchMode) {
ForceSwitchMode = forceSwitchMode;
}
}
and
import javax.xml.bind.annotation.XmlAttribute;
public class ForceSwitchMode {
private String name;
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and
import javax.xml.bind.annotation.XmlAttribute;
public class Obj {
String type;
String impactAnalysisDataBuilderClassName;
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#XmlAttribute
public String getImpactAnalysisDataBuilderClassName() {
return impactAnalysisDataBuilderClassName;
}
public void setImpactAnalysisDataBuilderClassName(String impactAnalysisDataBuilderClassName) {
this.impactAnalysisDataBuilderClassName = impactAnalysisDataBuilderClassName;
}
}
I am getting null list when doing the unmarshalling. This is the class where i create the JAXBcontext object and create unmarshalling object.
import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class CircuitImpactConfUnmarshaller {
public static void main(String[] args) throws JAXBException {
File file = new File("CircuitImpact.xml");
System.out.println(file.exists());
JAXBContext jaxbContext = JAXBContext.newInstance(CircuitImpactConfigs.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
CircuitImpactConfigs que = (CircuitImpactConfigs) jaxbUnmarshaller.unmarshal(file);
System.out.println(que.getForceSwitchMode().getName());
List<Obj> list = que.getObject();
System.out.println(list);
}
}
the last print statement is giving null. I understand i am doing something wrong in the class Obj
JAXB uses implicit naming conventions and explicit annotations to define a mapping between a XML and a Java structure.
Either element and attribute names in the XML match field names in Java (match by naming convention) or you need to use annotations to establish the mapping.
The Java list CircuitImpactConfigs.Object is not getting filled because the mapping failed, since the corresponding element in the XML is named Objects.
You can now either rename CircuitImpactConfigs.Object to CircuitImpactConfigs.Objects or use the name parameter of a JAXB annotation to define the corresponding name:
#XmlElement(name="Objects")
public List<Obj> getObject() {
EDIT: As you indicate in your comments there are still other mapping issues with your code. I would suggest that you adapt another approach:
Create a CircuitImpactConfigs object with all subobjects filled.
Marhsall that object to a XML file.
Check that the XML is in the expected format. If not, tweak the mapping.
Following this approach you can be sure that a XML file in the desired format can be unmarshalled to your Java structure. The code to marshall is
CircuitImpactConfigs que = ...
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(que, System.out);

I want to insert subelement to a subelement in xml tree using Java

#XmlRootElement
public class Dekkey {
String keyVal;
String kek1;
public String getKek1() {
return kek1;
}
#XmlElement
public void setKek1(String kek1) {
this.kek1 = kek1;
}
public String getKeyval() {
return keyVal;
}
#XmlAttribute
public void setKeyval(String inpKey) {
this.keyVal = inpKey;
}
}
This is my code snippet, where I want to insert a sub-element called userkey to the sub-element kek1. How can I do that?
How to insert attribute value for those sub-elements? I have another class called MarshDemo in which an object of Dekkey is created and then setkeyVal() function is called by passing value to the function.
The output looks like this:
<Dekkey keyVal="xer">
<kek1 keyVal="biv">
<userkey keyVal="wed">
</userkey>
</kek1>
</Dekkey>
I have omitted the getters and setters for brevity, this is what your should look like.
#XmlRootElement
public class Dekkey {
#XmlAttribute
String keyVal;
Kek1 kek1;
}
#XmlElement(name="kek1")
public class Kek1 {
#XmlAttribute
String keyVal;
UserKey userkey;
}
#XmlElement(name="userkey")
public class UserKey {
#XmlAttribute
String keyVal;
}
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Dekkey
Below is how you could map your use case using MOXy's #XmlPath extension (see: http://blog.bdoughan.com/2010/07/xpath-based-mapping.html).
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name="Dekkey")
#XmlAccessorType(XmlAccessType.FIELD)
public class Dekkey {
#XmlAttribute
String keyVal;
#XmlPath("kek1/#keyVal")
String kek1;
#XmlPath("kek1/userkey/#keyVal")
String userKey;
}
jaxb.properties
To specify MOXy as your JAXB (JSR-222) provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Dekkey.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum16248263/input.xml");
Dekkey dekkey = (Dekkey) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(dekkey, System.out);
}
}
input.xml/Output
<?xml version="1.0" encoding="UTF-8"?>
<Dekkey keyVal="xer">
<kek1 keyVal="biv">
<userkey keyVal="wed"/>
</kek1>
</Dekkey>

Marshalling/unmarshalling fields to tag with attributes using JAXB

Let's say I have class Example:
class Example{
String myField;
}
I want to unmarshal it in this way:
<Example>
<myField value="someValue" />
</Example>
Is it possible to unmarshal object in such way using JAXB XJC? ( I know about XmlPath in EclipseLink, but can't use it).
You could leverage an XmlAdapter for this use case. In that XmlAdapter you will convert a String to/from an object that has one property mapped to an XML attribute.
XmlAdapter
package forum12914382;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class MyFieldAdapter extends XmlAdapter<MyFieldAdapter.AdaptedMyField, String> {
#Override
public String unmarshal(AdaptedMyField v) throws Exception {
return v.value;
}
#Override
public AdaptedMyField marshal(String v) throws Exception {
AdaptedMyField amf = new AdaptedMyField();
amf.value = v;
return amf;
}
public static class AdaptedMyField {
#XmlAttribute
public String value;
}
}
Example
package forum12914382;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement(name="Example")
#XmlAccessorType(XmlAccessType.FIELD)
class Example{
#XmlJavaTypeAdapter(MyFieldAdapter.class)
String myField;
}
Demo
package forum12914382;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Example.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum12914382/input.xml");
Example example = (Example) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(example, System.out);
}
}
input.xml/Output
<Example>
<myField value="someValue" />
</Example>
Related Example
JAXB Element mapping
Yes, manually add the #XmlAttribute-Annotation or generate the classes from an XSD.

JAXB location in file for unmarshalled objects

I have some objects being unmarshalled from an XML file by JAXB. Is it possible to have JAXB tell me or somehow find out where in the XML file (line and column) each object comes from?
This information is available at some point, because JAXB gives it to me during schema validation errors. But I would like to have it available for validated objects too.
You could do this in JAXB by leveraging an XMLStreamReader and an Unmarshaller.Listener:
Demo
package forum383861;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Unmarshaller.Listener;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
FileInputStream xml = new FileInputStream("src/forum383861/input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
Unmarshaller unmarshaller = jc.createUnmarshaller();
LocationListener ll = new LocationListener(xsr);
unmarshaller.setListener(ll);
Customer customer = (Customer) unmarshaller.unmarshal(xsr);
System.out.println(ll.getLocation(customer));
System.out.println(ll.getLocation(customer.getAddress()));
}
private static class LocationListener extends Listener {
private XMLStreamReader xsr;
private Map<Object, Location> locations;
public LocationListener(XMLStreamReader xsr) {
this.xsr = xsr;
this.locations = new HashMap<Object, Location>();
}
#Override
public void beforeUnmarshal(Object target, Object parent) {
locations.put(target, xsr.getLocation());
}
public Location getLocation(Object o) {
return locations.get(o);
}
}
}
input.xml
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<address/>
</customer>
Output
[row,col {unknown-source}]: [2,1]
[row,col {unknown-source}]: [3,5]
Customer
package forum383861;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address
package forum383861;
public class Address {
}
For More Information
http://blog.bdoughan.com/2011/08/using-unmarshallerlistener-to-capture.html
I'm afraid not. JAXB builds on top of a XML parser, this one will have built up a logical representation of your XML document forgetting the original string representation of your document.
The validation step is done while your string is still read in, so your parser is able to give you an error message telling you the position of the error. JAXB will only bypass that error message. But as soon as the XML is validated and parsed, only the logical representation will exist.

How to add an XML namespace (xmlns) when serializing an object to XML

I'm serializing Objects to XML with the help of XStream.
How do I tell XStream to insert an xmlns to the XML output of my object?
As an example, I have this simple object I want to serialize:
#XStreamAlias(value="domain")
public class Domain
{
#XStreamAsAttribute
private String type;
private String os;
(...)
}
How do I achieve exactly the following output with XStream?
<domain type="kvm" xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0">
<os>linux</os>
</domain>
XStream doesn't support namespaces but the StaxDriver it uses, does. You need to set the details of your namespace into a QNameMap and pass that into the StaxDriver:
QNameMap qmap = new QNameMap();
qmap.setDefaultNamespace("http://libvirt.org/schemas/domain/qemu/1.0");
qmap.setDefaultPrefix("qemu");
StaxDriver staxDriver = new StaxDriver(qmap);
XStream xstream = new XStream(staxDriver);
xstream.autodetectAnnotations(true);
xstream.alias("domain", Domain.class);
Domain d = new Domain("kvm","linux");
String xml = xstream.toXML(d);
Output:
<qemu:domain type="kvm" xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0">
<qemu:os>linux</qemu:os>
</qemu:domain>
Alternatively, this use case could be handled quite easily with a JAXB implementation (Metro, EclipseLink MOXy, Apache JaxMe, etc):
Domain
package com.example;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Domain
{
private String type;
private String os;
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
}
package-info
#XmlSchema(xmlns={
#XmlNs(
prefix="qemu",
namespaceURI="http://libvirt.org/schemas/domain/qemu/1.0")
})
package com.example;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;
Demo
package com.example;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Domain.class);
Domain domain = new Domain();
domain.setType("kvm");
domain.setOs("linux");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(domain, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<domain xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0" type="kvm">
<os>linux</os>
</domain>
For More Information
http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html
http://bdoughan.blogspot.com/2010/10/how-does-jaxb-compare-to-xstream.html
This is a bit of a hack, but it's quick and easy: add a field to your class called xmlns, and only have it non-null during serialisation. To continue your example:
#XStreamAlias(value="domain")
public class Domain
{
#XStreamAsAttribute
private String type;
private String os;
(...)
#XStreamAsAttribute
#XStreamAlias("xmlns:qemu")
String xmlns;
public void serialise(File path) {
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(Domain.class);
(...)
PrintWriter out = new PrintWriter(new FileWriter(path.toFile()));
xmlns = "http://libvirt.org/schemas/domain/qemu/1.0";
xstream.toXML(this, out);
xmlns = null;
}
}
To be complete, setting xmlns = null should be in a finally clause. Using a PrintWriter also allows you to insert an XML declaration at the start of the output, if you like.

Categories

Resources