I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.
ex: I want root tag to be
<report>
<id>rep 1</id>
</report>
, But getting as
<ns2:report>
....
</ns2:report>
In the generated java class, I gave annotation as #XmlRootElement(name="report",namespace="urn:report")
Can some one pls help
If this is your class:
package example;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="report",namespace="urn:report")
public class Root {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Then it makes sense that there is a prefix on the root element, because you have specified that the "root" element is namespace qualified and the "id" element is not.
<ns2:report xmlns:ns2="urn:report">
<id>123</id>
</ns2:report>
If you add a package-info class to your model, you can leverate the #XmlSchema annotation:
#XmlSchema(
namespace = "urn:report",
elementFormDefault = XmlNsForm.QUALIFIED)
package example;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
Then the JAXB implementation may choose to leverage the default namespace, but note now all of the elements are namespace qualified which may or may not match your XML schema:
<report xmlns="urn:report">
<id>123</id>
</report>
For more information on JAXB and namespaces see:
http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html
Take a look at this answer. It describes how to use a SAX Filter to remove any namespace.
The blog entry Customizing JAXB shows the alternatives provided by implementing a PreferredMapper . Unfortunately it explains, that is not possible to fully suppress namespaces.
Use this attribute in your root element of your schema: elementFormDefault="qualified"
So for instance:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
Somehow the accepted answer did not work for me. I got success when I found solutions in some related stockOverflow questions involving DelegatingXMLStreamWriter from cxf and a filter, NoNamesWriter. The implementation I used with NoNamesWriter:
public class NoNamesWriter extends DelegatingXMLStreamWriter
{
#Override
public void writeStartElement(String prefix, String local, String uri) throws XMLStreamException {
delegate.writeStartElement("", local, uri);
}
public static XMLStreamWriter filter(FileOutputStream fileOutputStream) throws XMLStreamException {
return new NoNamesWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream));
}
public NoNamesWriter(XMLStreamWriter writer) {
super(writer);
}
}
Invoke the same as described here, like:
xmlmarshaller.marshal(xc, NoNamesWriter.filter(new FileOutputStream(outfile, false));
Related
If I have a XML with huge header tags but I need to get only the list of objects dppc and child object ppc. Please advise how to get the values only from the node dppc.
<SOAPENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAPENV:Body>
<rpc:distributeObject xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rpc="http://company.xxx.com/Distributed/Object">
<standardHeader xmlns="http://wsi.nat.bat.com/2005/06/StandardHeader/">
<dppc>
<ppc>
<productName>Export1</productName>
</ppc>
<ppc>
<productName>Export2</productName>
</ppc>
</dppc>
</standardHeader>
</rpc:distributeObject>
</SOAPENV:Body>
Please find the below code to unmarshal it
String example =
"<SOAPENV:Envelope xmlns:SOAPENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><SOAPENV:Body><rpc:distributeObject xmlns:SOAPENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:rpc=\"http://company.xxx.com/Distributed/Object\"><standardHeader xmlns=\"http://wsi.nat.bat.com/2005/06/StandardHeader/\"><dppc><ppc><productName>Export1</productName></ppc><ppc><productName>Export2</productName></ppc></dppc></standardHeader></rpc:distributeObject></SOAPENV:Body>";
message = MessageFactory.newInstance().createMessage(null,
new ByteArrayInputStream(example.getBytes()));
Unmarshaller unmarshaller = JAXBContext.newInstance(Dppc.class).createUnmarshaller();
Dppc dppc = (Dppc)unmarshaller.unmarshal(message.getSOAPBody().extractContentAsDocument());
dppc.getPPC();
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
class Dppc{
#XmlPath("rpc:distributeObject/standardHeader/dppc")
private List<PPC> ppC;
public List<PPC> getPPC() {
return ppC;
}
public void setPPC(List<PPC> ppC) {
this.ppC= ppC;
}
}
class PPC {
String productName;
//getter & setters;
}
I have created a package-info file also, but it is not working.
With the pure Implementation of JAXB this is not possible because JAXB don't support XPath by default.
One possible solution is to use EclipseLink(MOXy) which supports the #XmlPath Annotation.
With that annotation it is possible to define the Path of an Element inside the XML. For your XML to read only the dppc Elements and childs your class would look something like this (not tested):
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name="SOAPENV:Body")
public class MainElement{
#XmlPath("rpc:distributeObject/standardHeader/dppc")
DPPC dppc;
//getter and setters
}
Same for the dppc and ppc class.
The Link to MOXy give you some nice examples.
We have a complicated structure of classes that we are trying to marshal to an xml file using JAXB-RI. The marshalling seems to work correctly with Spring's jaxb2Marshaller but not with the jaxb-ri, which is what we are trying to use. (We're using Java 6 and jaxb-2.1.13)
This is an example of the output we currently see after marshalling with JAXB-RI:
<?xml version="1.0" encoding="UTF-8"?>
<specificCompanyList>
<org>com.ourcompany.etc.etc.TypeOfCompany#56cb0eed</org>
<org>com.ourcompany.etc.etc.TypeOfCompany#3125a57</org>
....
</specificCompanyList>
This is what we want to see:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<specificCompanyList>
<org id="123456" name=" COMPANY NAME 1"/>
<org id="098765" name=" COMPANY NAME 2"/>
....
</specificCompanyList>
Here is some info about our class structure. Apologies if it's confusing -- I want to lay everything out on the table. Class names and paths have been changed and shortened as well.
Class that becomes the root element:
#XmlRootElement(name="specificCompanyList")
public class SpecificCompanyLookup extends BaseCompanyLookup<TypeOfCompany> {
public SpecificCompanyLookup() {}
....
}
BaseCompanyLookup:
#XmlAccessorType(XmlAccessType.FIELD)
abstract class BaseCompanyLookup<T extends OrgNode> implements Lookup {
#XmlElement(name="org")
final Set<T> companyList = new TreeSet<T>(.....);
}
OrgNode:
#XmlAccessorType(XmlAccessType.FIELD)
classOrgNode extends BaseLookupItem {
}
BaseLookupItem:
#XmlAccessorType(XmlAccessType.FIELD)
public class BaseLookupItem {
#XmlAttribute(required = true)
protected String id;
#XmlAttribute(required = true)
protected String name;
....
}
A class that extends OrgNode:
class TypeOfCompany extends OrgNode {
....
}
So:
BaseLookupItem -> OrgNode -> TypeOfCompany
Does anyone know what is causing this bad output? How do we make the JAXB-RI marshaller generate the output that we need?
EDIT: We found the solution. This happened when we moved to WebLogic 12c, which has switched its JAXB default to the EclipseLink MOXy implementation. That implementation appears to have a bug for the case I described here. Following the instructions to switch to the Glassfish JAXB RI fixed this issue for us. Here are those instructions: http://docs.oracle.com/cd/E24329_01/web.1211/e24964/data_types.htm#CIHBHDGI
I confirmed this is in fact a bug in MOXy and have opened the following bug to track the issue https://bugs.eclipse.org/bugs/show_bug.cgi?id=410001
I also confirmed that adding the #XmlSeeAlso annotation like this would be a workaround for this case.
#XmlSeeAlso(TypeOfCompany.class)
public class SpecificCompanyLookup extends BaseCompanyLookup<TypeOfCompany> {
public SpecificCompanyLookup() {}
}
I'm new to using namespaces in xml so I am kind of confused and would like some clarification. I have a java service where I am receiving xml documents with many different namespaces and while i got it working, I feel like I must have done something wrong so I want to check. In my package-info.java I have my schema annotation such as:
#javax.xml.bind.annotation.XmlSchema(
xmlns={
#javax.xml.bind.annotation.XmHS(prefix="train", namespaceURI="http://mycompany/train"),
#javax.xml.bind.annotation.XmHS(prefix="passenger", namespaceURI="http://mycompany/passenger")
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm=QUALIFIED
)
I have a Train.java annotated on the class level with:
#XmlRootElement(name="Train", namespace="http://mycompany/train")
and each field in the class annotated with:
#XmlElement(name="Color") for example
Train contains a List of Passenger(s) so there's a property
private Set<Passenger> passengers;
and this collection is annotated with:
#XmlElementWrapper(name="Passengers")
#XmlElements(#XmlElement(name="Passenger", namespace="http://mycompany/passenger"))
Then within Passenger.java the class itself is annotated with:
#XmlElement(name="Passenger", namespace="http://mycompany/passenger")
Finally for individual fields within Passenger.java, they are annotated like this:
#XmlElement(name="TicketNumber", namespace="http://mycompany/passenger")
So when I have an xml that looks like:
<train:Train>
<train:Color>Red</train:Color>
<train:Passengers>
<train:Passenger>
<passenger:TicketNumber>T101</passenger:TicketNumber>
</train:Passenger>
</train:Passengers>
</train:Train>
Now I unmarshal this xml I received and Train's Color property is set and Passenger's TicketNumber property is set. But I don't know why I need to add the namespace url on the XmlElement annotation on TicketNumber for that to work but I didn't need to do so for the Color property on Train. If I remove the namespace attribute from the XmlElement annotation on TicketNumber, the value from the xml wont get mapped to the object unless I also remove the namespace prefix from the xml request. I feel like since I've got the namespace attribute defined on the XmlRootElement for Passenger, I shouldn't need to do that for every single field in the class as well just like I didn't have to for Train so I am assuming I must have setup something wrong. Can someone point me in the right direction? Thanks!
Below is an explanation of how namespaces work in JAXB (JSR-222) based on your model.
JAVA MODEL
package-info
Below is a modified version of your #XmlSchema annotation. It contains some key information:
namespace - The default namespace that will be used to qualify global elements (those corresponding to #XmlRootElement and #XmlElementDecl annotations (and local elements based on the elementFormDefault value) that don't have another namespace specified.
elementFormDefault by default only global elements are namespace qualified but by setting the value to be XmlNsForm.QUALIFIED all elements without an explicit namespace specified will be qualified with the namespace value.
xmlns is the preferred set of prefixes that a JAXB impl should use for those namespaces (although they may use other prefixes).
#XmlSchema(
namespace="http://mycompany/train",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns={
#XmlNs(prefix="train", namespaceURI="http://mycompany/train"),
#XmlNs(prefix="passenger", namespaceURI="http://mycompany/passenger")
}
)
package forum15772478;
import javax.xml.bind.annotation.*;
Train
Since all the elements corresponding to the Train class correspond to the namespace specified on the #XmlSchema annotation, we don't need to specify any namespace info.
Global Elements - The #XmlRootElement annotation corresponds to a global element.
Local Elements - The #XmlElementWrapper and #XmlElement annotations correspond to local elements.
package forum15772478;
import java.util.List;
import javax.xml.bind.annotation.*;
#XmlRootElement(name="Train")
public class Train {
private List<Passenger> passengers;
#XmlElementWrapper(name="Passengers")
#XmlElement(name="Passenger")
public List<Passenger> getPassengers() {
return passengers;
}
public void setPassengers(List<Passenger> passengers) {
this.passengers = passengers;
}
}
Passenger
If all the elements corresponding to properties on the Passenger class will be in the http://mycompany/passenger namespace, then you can use the #XmlType annotation to override the namespace from the #XmlSchema annotation.
package forum15772478;
import javax.xml.bind.annotation.*;
#XmlType(namespace="http://mycompany/passenger")
public class Passenger {
private String ticketNumber;
#XmlElement(name="TicketNumber")
public String getTicketNumber() {
return ticketNumber;
}
public void setTicketNumber(String ticketNumber) {
this.ticketNumber = ticketNumber;
}
}
Alternatively you can override the namespace at the property level.
package forum15772478;
import javax.xml.bind.annotation.*;
public class Passenger {
private String ticketNumber;
#XmlElement(
namespace="http://mycompany/passenger",
name="TicketNumber")
public String getTicketNumber() {
return ticketNumber;
}
public void setTicketNumber(String ticketNumber) {
this.ticketNumber = ticketNumber;
}
}
DEMO CODE
The following demo code can be run to prove that everything works:
Demo
package forum15772478;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Train.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum15772478/input.xml");
Train train = (Train) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(train, System.out);
}
}
input.xml/Output
In the XML below I have added the necessary namespace declarations that were missing from the XML document in your question.
<train:Train
xmlns:train="http://mycompany/train"
xmlns:passenger="http://mycompany/passenger">
<train:Color>Red</train:Color>
<train:Passengers>
<train:Passenger>
<passenger:TicketNumber>T101</passenger:TicketNumber>
</train:Passenger>
</train:Passengers>
</train:Train>
FOR MORE INFORMATION
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
I have xml like this
<abc:city>
<def:cityname />
<xyz:postalTown>
Sacramento
</xyz:postalTown>
</abc:city>
<abc:city>
<def:cityname />
<pqr:postalTown>
Sacramento
</pqr:postalTown>
</abc:city>
Can xstream handle these namespaces like 'abc' in <abc:city>
Also namespace for <pqr:postalTown> can be changed as I am unaware of the response coming. How can this be handled dynamically through xstream.
If this is impossible in xstream; can it be handled using jaxb?
EDIT:
My class will be City:
Class City{
String cityName;
String postalTown;
}
How can I map above xml to City class as tags contain prefixes?
UPDATE
If the prefixes do not correspond to namespace declarations, then you could use the approach from the answer I linked below from a related question:
https://stackoverflow.com/a/11970622/383861
NOTE ABOUT NAMESPACE QUALIFICATION
The prefixes used don't come into play in terms of object-to-XML mapping. As long as the the xyz and pqr prefixes correspond to the same namespace you will be fine with any object-to-XML solution that supports namespaces.
Even though the following documents contain different prefixes they have the same namespace qualification.
Document #1
<abc:city xmlns:abc="ABC" xmlns:def="DEF" xmlns:ghi="XYZ">
<def:cityName/>
<ghi:postalTown>
Sacramento
</ghi:postalTown>
</abc:city>
Document #2
<jkl:city xmlns:jkl="ABC" xmlns:mno="DEF" xmlns:pqr="XYZ">
<mno:cityName/>
<pqr:postalTown>
Sacramento
</pqr:postalTown>
</jkl:city>
JAXB AND NAMESPACES
Below is how you would map your City class to the XML documents above. Note how it is the namespace URI and not the prefix that is specified on the #XmlRootElement and #XmlElement annotations.
package forum11932402;
import javax.xml.bind.annotation.*;
#XmlRootElement(namespace="ABC")
public class City {
#XmlElement(namespace="DEF")
String cityName;
#XmlElement(namespace="XYZ")
String postalTown;
}
Below is some information on JAXB and namespaces:
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
DEMO CODE
The following demo code can be used to unmarshal either of the XML documents I have posted earlier in this answer.
package forum11932402;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(City.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11932402/input.xml");
City city = (City) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(city, System.out);
}
}
Below is the output from running the demo code. The JAXB implementation has assigned new prefixes. The cityName element is still namespace qualified, it just corresponds to the default namespace which was declared as xmls="DEF".
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:city xmlns="DEF" xmlns:ns2="XYZ" xmlns:ns3="ABC">
<cityName></cityName>
<ns2:postalTown>
Sacramento
</ns2:postalTown>
</ns3:city>
I'm using a POJO object with XmlType for a custom XML adapter I built for marshaling a map of strings. I'm having issues however, with getting it to allow me to use null values properly. I was able to get it to work, but I'm not happy with the XML it is generating.
This is what I'm currently using that I would like to work, but as you can see in an sample XML result, it is not including the proper xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" value
#XmlType(name="element")
public class RestMapElements {
#XmlAttribute(name="name")
public String key;
#XmlValue
public String value;
public RestMapElements(String key, String value) {
this.key = key;
this.value = value;
}
}
The resulting XML (slimmed to relevant data).
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
...
<element-list>
<item name="activated_date">2012-03-29 11:34:14.323</item>
<item name="some_null_value"/>
</element-list>
...
However, I was able to get it to work with this, I'm just not happy with the XML having to add an additional "value" tag inside of the item tag to get it to work. (side note, why is it naming it item instead of element like I tried to specify in the XmlType name declaration?)
#XmlType(name="element")
public class RestMapElements {
#XmlAttribute(name="name")
public String key;
#XmlElement(nillable = true)
public String value;
public RestMapElements(String key, String value) {
this.key = key;
this.value = value;
}
}
Again, the resulting XML (slimmed to relevant data).
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
...
<element-list>
<item name="activated_date"><value>2012-03-29 11:34:14.323</value></item>
<item name="some_null_value"><value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/></item>
</element-list>
...
Really, I can use the second as it works to solve my issue. I'm just wanting to use this as a learning experience to see if JAXB using annotations will allow be to bend this to what I'm looking for without having to add that additional value tag underneath an item tag just so I can support null values. Right now, when it unmarshals in the first example, I end up getting empty strings instead of null. In the second example, I get the null value I was expecting.
FYI: I'm currently using Jersey 1.11
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You could use MOXy's #XmlNullPolicy extension to map this use case:
RestMapElements
package forum10415075;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
#XmlType(name="element")
public class RestMapElements {
#XmlAttribute(name="name")
public String key;
#XmlValue
#XmlNullPolicy(nullRepresentationForXml=XmlMarshalNullRepresentation.XSI_NIL)
public String value;
}
Root
package forum10415075;
import java.util.*;
import javax.xml.bind.annotation.*;
#XmlRootElement
public class Root {
#XmlElementWrapper(name="element-list")
#XmlElement(name="item")
public List<RestMapElements> items = new ArrayList<RestMapElements>();
}
jaxb.properties
To use MOXy as your JAXB (JSR-222) provider you need to add a file called jaxb.properties in the same package as your domain model with the following content:
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
package forum10415075;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum10415075/input.xml");
Root root = (Root) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
input.xml/Output
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element-list>
<item name="activated_date">2012-03-29 11:34:14.323</item>
<item name="some_null_value" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</element-list>
</root>
Note
If you are using Jersey in GlassFish 3.1.2 MOXy or WebLogic 12.1.1 is already included:
http://blog.bdoughan.com/2012/02/glassfish-312-is-full-of-moxy.html
http://blog.bdoughan.com/2011/12/eclipselink-moxy-is-jaxb-provider-in.html
I see your problem. An item element with xsi:nil="true" will be generated only by setting the corresponding RestMapElements entry in your ArrayList (or whatever) to null, losing the attribute. I think there isn't much of a solution to this.
One option would be to use your marshalling from the beginning of your post and unmarshal using the following:
If you're doing something like this:
#XmlElementWrapper(name="element-list")
#XmlElement(name="item")
public ArrayList<RestMapElements> list;
You can use a XmlAdapter to check if the value is an empty String and set it to null if it is:
#XmlElementWrapper(name="element-list")
#XmlElement(name="item")
#XmlJavaTypeAdapter(ItemAdapter.class)
public ArrayList<RestMapElements> list;
And ItemAdapter:
public class ItemAdapter extends XmlAdapter<RestMapElements, RestMapElements> {
#Override
public RestMapElements unmarshal(RestMapElements v) throws Exception {
if (v.value.equals("")) v.value = null;
return v;
}
}
Although this is still inelegant imho.
If you want to generate the proper xsi:nil="true" item elements, this is obviously not what you want though.
Good luck.