javax.xml.bind.UnmarshalException: Unexpected element. What am i missing? - java

I am doing this,
JAXBContext jaxbContext = JAXBContext.newInstance(new Class[] {
mine.beans.ObjectFactory.class });
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
orderhistory = (OrderHistory) unmarshaller.unmarshal(new StreamSource(
new StringReader(responseXML)));`
I am getting javax.xml.bind.UnmarshalException: Unexpected element "OrderHistory". Expected elements are "{_http://orderhistory.shc.com/common/domain}OrderHistory". but i checked my OrderHistory.java i have the
#XmlRootElement(name = "OrderHistory")
public class OrderHistory{
What am i missing???
Even the package-info.java file is also present
Here is my response xml,
<?xml version="1.0" encoding="UTF-8"?>
<OrderHistory>
<guid>5555</guid>
<syNumber xsi:nil="true"></syNumber>
<email xsi:nil="true"></email>
<totalPages>0</totalPages>
</OrderHistory>
Still i am facing the same issue???
I ve made changes to my package-info.java i have removed the namespace attribute but still i am seeing the same issue,
#javax.xml.bind.annotation.XmlSchema()
package mine.beans;

It appears as though your input document is not namespace qualified.
You have:
<OrderHistory>...</OrderHistory>
And your JAXB (JSR-222) implementation is expecting:
<OrderHistory xmlns="_http://orderhistory.shc.com/common/domain">...</OrderHistory>
Related
If you are unmarshalling from a DOM, make sure to call setNamespaceAware(true) on the instance of DocumentBuilderFactory.
For More Information
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html

As hint. Try to marshal the document from your object, and see if the tags are written as expected.

Did you try to modify your XML? Your UNmarshaller is expecting the OrderHistory-Element to be part of the "http://orderhistory.shc.com/common/domain" namespace, and yet it isnt. You could give this a try:
<?xml version="1.0" encoding="UTF-8"?>
<OrderHistory xmlns="_http://orderhistory.shc.com/common/domain">
<guid>5555</guid>
<syNumber xsi:nil="true"></syNumber>
<email xsi:nil="true"></email>
<totalPages>0</totalPages>
</OrderHistory>

Related

how to skip XSD:type while unmarshalling?

i received the xml
<?xml version="1.0" encoding="UTF-8"?>
<ns1:paymentResponse xmlns:ns1="urn:Brifastservice">
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="tns:paymentAccount_CT_Result">
<message xsi:type="xsd:string">[ERROR] Reference Number Same </message>
<status xsi:type="xsd:string">2007</status>
</return>
</ns1:paymentResponse>
i want to unmarshal it , i am using below code
JAXBContext jaxbContext = JAXBContext.newInstance(PaymentResponse.class);
Unmarshaller um = jaxbContext.createUnmarshaller();
StringReader resRreader = new StringReader(res);
final SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(true);
final XMLReader reader = sax.newSAXParser().getXMLReader();
final Source er = new SAXSource(reader, new InputSource(resRreader));
PaymentResponse response = (PaymentResponse)um.unmarshal(er);
return response.getReturnResponse().getMessage();
but I got the exception
prefix xsd is not bound to a namespace
If I use
sax.setNamespaceAware(false);
then I get
javax.xml.bind.UnmarshalException:
unexpected element (uri:"", local:"ns1:paymentResponse").
Expected elements are <{urn:someService}paymentResponse>
please suggest how to unmarshal? I have package info
#javax.xml.bind.annotation.XmlSchema(
namespace = "urn:someService",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
The XML document uses XSI to declare the XSD type of the elements, but the XSD namespace is not defined anywhere inside this document.
A quick and dirty solution would be to modify the string with the received XML document and forcefully add a xmlns:xsd="http://www.w3.org/2001/XMLSchema" declaration in the root element before it is parsed.
The proper soluction is to create a custom ContentHandler that intercepts the startDocument, endDocument, startPrefixMapping and endPrefixMapping events and makes uses of NamespaceSupport object to keep track of the declared namespaced and also inject the missing XSD namespace. An example of this (minus the injected namespace) can be found in the chapter Receiving Namespace Mappings of Processing XML with Java, available online at http://www.cafeconleche.org/books/xmljava/chapters/ch06s09.html.

JAXB unmarshall xml without package-info.java

JAXB unmarshaller throws exception if there is no package-info.java file. This code is called from another language and custom classloader can not load package-info properly.
I had already manually added the namespace parameter to all the #XmlElement annotations.
Xml root element has multiple xmlns attributes. Two of them (xmlns and xmlns:c) have the same value (I can not change xml, which is comeing from external service)
BUT: It works if I remove xmlns="urn:foo:bar" from document even without package-info
The question: how can I unmarshall without package-info (I can not modify custom classloader which can not load it) and without removing xmlns from xml ?
What should I change in my code?
Java 1.6_45 vJAXB 2.1.10
XML root element sample:
<?xml-stylesheet type="text/xsl" href="file1.xslt">
<?xml-stylesheet type="text/xsl" href="file1.xslt"?>
<c:ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:foo:ba" xmlns:c="urn:foo:bar" xmlns:std="urn:foo:std"
xsi:schemaLocation="urn:foo:bar file2.xsd">
Code:
String path = "D:\\data\\document.xml";
try {
JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller u = jc.createUnmarshaller();
Object root = u.unmarshal(new File(path)); //exception w/o package-info.java
CDocument doc= (CDocument) JAXBIntrospector.getValue(root);
System.out.println(doc);
package-info.java
#javax.xml.bind.annotation.XmlSchema(namespace = "urn:foo:bar", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
xmlns={#XmlNs(namespaceURI = "urn:foo:bar", prefix = "")})
package test.model;
import javax.xml.bind.annotation.XmlNs;
Exception:
javax.xml.bind.UnmarshalException: Unable to create an instance of my.package.here.model.ANY
Any ideas will be greatly appreciated, I had spent so much time trying, but still have nothing.
BUT: It works if I remove xmlns="urn:foo:bar" from document even without package-info
This means that you have not added the namespace parameter everywhere you need to.
In the XML document below without the #XmlSchema annotation to map the namespace qualification, you would require the namespace parameter on the #XmlRootElement annotation for the Foo class and the #XmlElement annotation on the bar property.
<foo xmlns="http://www.example.com">
<bar>Hello World</bar>
</foo>

Error on unmarshaling with generated code (moxy): "A descriptor with default root element ... was not found in the project"

I generated code using moxy for different xsd-Files:
http://www.forum-datenaustausch.ch/generalinvoiceresponse_400.xsd
and
http://www.forum-datenaustausch.ch/xmlstandards_generelle_rechnung_beispiele_antwort_4.3_20100901.zip
I generated jaxb-classes for both xsd (using moxy). Then i tried unmarshal xml-files (genrated by eclipse) with this code:
public void tempTest() throws JAXBException{
JAXBContext jC = JAXBContext.newInstance(<package for corresponding type>.ResponseType.class);
jC.createUnmarshaller().unmarshal(ResponseTest.class.getResourceAsStream("/responses/generalInvoiceResponse_400.xml"));
}
With xml-File of 4.3-type (2nd link) this works fine but with xml of 400-type (1st link) i get this error:
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element {http://www.forum-datenaustausch.ch/de}response was not found in the project]
It seems to be a problem with the name-space. The name space is different but i can not see a relevant difference in generated code or generated xml - the name space is consistent.
so what could cause this problem (where is the difference) and how to solve it?
small addition: i also tried to unmarshal xml marshaled with jaxb/moxy-code:
public void marshall() throws JAXBException, FileNotFoundException {
JAXBContext jC = JAXBContext.newInstance(ResponseType.class);
ObjectFactory of = new ObjectFactory();
jC.createMarshaller().marshal( of.createResponse(of.createResponseType()),new FileOutputStream("simpleresponse.xml"));
}
this creates an very simple xml:
<?xml version="1.0" encoding="UTF-8"?>
<response xmlns="http://www.forum-datenaustausch.ch/de"/>
unmarshaling this yields the same error.
When creating a JAXBContext based on a model generated from an XML Schema you should always use the the newInstance method that takes the package name. This will ensure that all the necessary bits are processed.
JAXBContext jC = JAXBContext.newInstance("ch.forum_datenaustausch.de");
When you use the JAXBContext.newInstance(Class...) method the JAXB implementation is assuming that you started from Jav classes. Since the role of ObjectFactory can be played by any class annotated with #XmlRegistry the ObjectFactory class generated from the XML schema will be automatically picked up. You could do the following, but I still recommend the above approach:
JAXBContext jC = JAXBContext.newInstance(ResponseType.class, ObjectFactory.class);
UPDATE
Thank you! but could you probably explain why it is working with one
xsd and not with the other?
The schema where it "works" may have a global element with an anonymous type which causes an #XmlRootElement annotation to be generated meaning the ObjectFactory is not required. The other may have a global element with a named complex type which causes an #XmlElementDecl annotation on an ObjectFactory class to be generated.
http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html
I also got same error message over WebLogic 12 but problem was due to namespace prefix.
It got fixed after explicitly adding name space in #Xmlrootelement(name="namespace:root tag name")

remove xmlns attribute from the root element while marshalling jaxb

This might be a related to JAXB Marshaller - How do I suppress xmlns namespace attributes?
But my problem is a little different.
I do the regular java marshalling and my xsd has no namespaces.The generated xml is without namespaces as well, except for the root element.
<?xml version="1.0" encoding="UTF-8"?><rootElement xmlns:ns2="unwanted namespace">
The unwanted namespace is from another schema from the same project and I am not sure why that is being picked up at this stage.
My rootElement.java generated by jaxb2-maven-plugin looks like :
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"feed"
})
#XmlRootElement(name = "rootElement", namespace = "")
public class RootElement{
....
}
At this point all I want is to get rid of the xmlns:ns2="unwanted namespace" attribute from the generated xml and I am struggling with it.
I looked at my package-info.java and it looks like:
#javax.xml.bind.annotation.XmlSchema(namespace = "unwanted namespace", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.mypackage;
I tried adding he -npa but it wont work on jaxb2-maven-plugin for some reason. I tried the NamespaceMapper but that works for changing prefixes. I could not get it to remove the namespace altogether. This is bothering me for a day now.
I have similar requirements at the moment. The only solution that worked for me is implementing a wrapper for XMLStreamWriter.
Please, take a look at my answer here. I've also described there other solutions I tried out.
Serialization using code from the link above looks like this:
XMLOutputFactory factory = XMLOutputFactory.newFactory();
StringWriter writer = new StringWriter(XML_BUFFER_INITIAL_SIZE);
XMLStreamWriter xmlWriter = null;
try {
xmlWriter = factory.createXMLStreamWriter(writer);
JAXBContext context = JAXBContext.newInstance(MyJAXBGeneratedClass.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(reportContainer, new NamespaceStrippingXMLStreamWriter(xmlWriter));
xmlWriter.flush();
}
finally {
if (xmlWriter != null)
xmlWriter.close();
}
return writer.toString();

Unmarshalling works incorrectly: javax.xml.bind.UnmarshalException: unexpected element

Got an exception
javax.xml.bind.UnmarshalException: unexpected element
(uri:"", local:"ConnectorCommandType")
trying to unmarshall xml, shown below:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ConnectorCommandType> ........ </ConnectorCommandType>
The exception basically says that element is not found in jaxb context. But debugging shows that this class is present and known in current jaxb context. The class ConnectorCommandType was generated from xsd xml as <xs:complexType> element.
Could there be an error in the xsd?
Has anyone faced with problem like that? Any suggestions? Thanks.
The solution depends on the answer to the following question:
Is there an #XmlRootElement(name="ConnectorCommandType") annotation on the ConnectorCommandType class, or an #XmlElementDecl(name="ConnectorCommandType") on a create method in the ObjectFactory class?
If the answer is YES
Is there a package-info in your generated model? It appears as though your JAXB (JSR-222) implementation is expecting a namespace qualified document. Something like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ConnectorCommandType xmlns="YOUR_NAMESPACE_HERE">
........
</ConnectorCommandType>
For More Information
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html
If the answer is NO
If the ConnectorCommandType element is not associated with a class, then you will need to
use one of the unmarshal methods that takes a class parameter.
http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html#unmarshal%28javax.xml.stream.XMLStreamReader,%20java.lang.Class%29

Categories