Unmarshalling error unexpected element uri

I get error while connecting to my web service: javax.xml.ws.soap.SOAPFaultException: Unmarshalling Error: unexpected element (uri:"", local:"OrderID"). Expected elements are ,&l...

I get error while connecting to my web service:

javax.xml.ws.soap.SOAPFaultException: Unmarshalling Error: unexpected
element (uri:»», local:»OrderID»). Expected elements are
<{}Login>,<{}CrewId>,<{}OrderID >,<{}OrderNumber >

Service is exposed using org.apache.cxf.transport.servlet.CXFServlet and jaxws:endpoint annotation. The client is generated using CXF. Firstly, suprising for me is that I’m using the same technology on both ends and the solution is not working, secondly, this mysterious {} in error messages.

So, what is wrong and how to understand this {}?

asked May 15, 2012 at 12:10

Danubian Sailor's user avatar

Danubian SailorDanubian Sailor

22.3k38 gold badges145 silver badges217 bronze badges

Have you noted space between OrderID and ‘>’? Expected is <{}OrderID > and you send >»OrderID». Check if you don’t have spaces in your element names.

While the above answer from Stepan Vihor helped you get what you needed, let me answer your question of what the «{}» means:

It means that the JAX-B Unmarshaller is expecting your OrderID element to have no namespace, i.e. the namespace uri for that element needs to be equal to «».

See here for a brief intro on XML Namespaces

answered Aug 21, 2012 at 17:57

icyitscold's user avatar

0

Have you noted space between OrderID and ‘>’? Expected is <{}OrderID > and you send "OrderID". Check if you don’t have spaces in your element names.

answered May 15, 2012 at 13:03

Stepan Vihor's user avatar

Stepan VihorStepan Vihor

1,0599 silver badges10 bronze badges

4

@icyitscold, the comment I want to add from my experience is
that you can change the elementFormDefault to «qualified» as
elementFormDefault="qualified"
in xs:schema element. The namespace will be qualified by default.

That’s for the WSDL-first approach, if you use code-first approach, you may consider add the change as

@javax.xml.bind.annotation.XmlSchema(
attributeFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED,
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)

answered Aug 15, 2014 at 20:14

chenrui's user avatar

chenruichenrui

8,2733 gold badges30 silver badges41 bronze badges

I got same error,

javax.xml.ws.soap.SOAPFaultException: Unmarshalling Error: unexpected element (uri:»», local:»country»). Expected elements are <{}seconds>,<{}month>,<{}hour>,<{}year>,<{}minutes>,<{}day>

Then I find on the web service side the response type added a new property ‘country’.

To ignore the new added property, add following propertys in ‘jaxws:client’ setting.

<jaxws:client id="abc"
              serviceClass="someClass"
              address="url">
    <jaxws:properties>
        <entry key="schema-validation-enabled" value="false"/>
        <entry key="set-jaxb-validation-event-handler" value="false"/>
    </jaxws:properties>
</jaxws:client>

answered Jan 25, 2018 at 3:09

Sonic.S.Xiang's user avatar

Sometimes you have to specify the names used in the wsdl (case sensitive):
<{Log}>, <{} CrewId>, <{} OrderID>, <{} OrderNumber>

@XmlElement(name = "CrewId")
protected String crewId;
@XmlElement(name = "OrderID ")
protected String orderID;
@XmlElement(name = "Login")
protected String login;
@XmlElement(name = "OrderNumber")
protected String orderNumber;

answered Sep 21, 2013 at 11:05

Abdelhafid's user avatar

AbdelhafidAbdelhafid

7597 silver badges13 bronze badges

I’m using jaxb2-marshaller to generate classes to communicate with a webservice. Java-classes are generated with use of some wsdl files.

Everything is okay now, but when I’m trying to use some of the generated classes, i got this unmarshalling error, altough I use the generated ObjectFactory classes.

Some of the stack:

org.springframework.ws.soap.client.SoapFaultClientException: Unmarshalling Error: unexpected element (uri:"http://xxxxxxxxx", local:"customer"). Expected elements are <{}customer> 
    at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:38)
    at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:826)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:621)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:373)
    at einvoice.service.CustomerService.createCustomer(CustomerService.java:40)
    at einvoice.controller.facturatie.FacturatieOverzichtController.handleRenderRequest(FacturatieOverzichtController.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

And my class:

@Service
public class CustomerService {

    @Autowired
    private WebServiceTemplate customerDaoTemplate;

    private ObjectFactory customerObjectFactory;

    public CustomerService() {
        customerObjectFactory = new ObjectFactory();    
    }

    public boolean createCustomer(Customer c)
    {
        System.out.println("CREATING CUSTOMER");
        einvoice.proxy.customerdaoservice.Customer customer = customerObjectFactory.createCustomer();
        customer.setConnectionURL("test");
        customer.setUid("testuid");
        customer.setName("KorneelTest");

        Create create = customerObjectFactory.createCreate();
        create.setCustomer(customer);

        try
        {
            customerDaoTemplate.marshalSendAndReceive(customerObjectFactory.createCreate(create));
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

It’s the createCustomer() method that shows this error.

The generated ObjectFactory class:

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2014.09.12 at 12:04:04 PM CEST 
//


package einvoice.proxy.customerdaoservice;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;


/**
 * This object contains factory methods for each 
 * Java content interface and Java element interface 
 * generated in the be.icredit.einvoice.proxy.customerdaoservice package. 
 * <p>An ObjectFactory allows you to programatically 
 * construct new instances of the Java representation 
 * for XML content. The Java representation of XML 
 * content can consist of schema derived interfaces 
 * and classes representing the binding of schema 
 * type definitions, element declarations and model 
 * groups.  Factory methods for each of these are 
 * provided in this class.
 * 
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _AbstractFilter_QNAME = new QName("http://xxxxxxx/", "abstractFilter");
    private final static QName _Customer_QNAME = new QName("http://xxxxxxx/", "customer");
    private final static QName _FindSingleResponse_QNAME = new QName("http://xxxxxxx/", "findSingleResponse");
    private final static QName _Create_QNAME = new QName("http://xxxxxxx/", "create");
    private final static QName _Find_QNAME = new QName("http://xxxxxxx/", "find");
    private final static QName _CreateResponse_QNAME = new QName("xxxxxxx/", "createResponse");
    private final static QName _FindResponse_QNAME = new QName("http://xxxxxxx/", "findResponse");
    private final static QName _UpdateResponse_QNAME = new QName("http://xxxxxxx/", "updateResponse");
    private final static QName _FindSingle_QNAME = new QName("http://xxxxxxx/", "findSingle");
    private final static QName _CustomerFilter_QNAME = new QName("http://xxxxxxx/", "customerFilter");
    private final static QName _Update_QNAME = new QName("http://xxxxxxx/", "update");
    private final static QName _AbstractEntity_QNAME = new QName("http://xxxxxxx/", "abstractEntity");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: be.icredit.einvoice.proxy.customerdaoservice
     * 
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link Update }
     * 
     */
    public Update createUpdate() {
        return new Update();
    }

    /**
     * Create an instance of {@link CustomerFilter }
     * 
     */
    public CustomerFilter createCustomerFilter() {
        return new CustomerFilter();
    }

    /**
     * Create an instance of {@link UpdateResponse }
     * 
     */
    public UpdateResponse createUpdateResponse() {
        return new UpdateResponse();
    }

    /**
     * Create an instance of {@link FindSingle }
     * 
     */
    public FindSingle createFindSingle() {
        return new FindSingle();
    }

    /**
     * Create an instance of {@link FindResponse }
     * 
     */
    public FindResponse createFindResponse() {
        return new FindResponse();
    }

    /**
     * Create an instance of {@link CreateResponse }
     * 
     */
    public CreateResponse createCreateResponse() {
        return new CreateResponse();
    }

    /**
     * Create an instance of {@link FindSingleResponse }
     * 
     */
    public FindSingleResponse createFindSingleResponse() {
        return new FindSingleResponse();
    }

    /**
     * Create an instance of {@link Customer }
     * 
     */
    public Customer createCustomer() {
        return new Customer();
    }

    /**
     * Create an instance of {@link Create }
     * 
     */
    public Create createCreate() {
        return new Create();
    }

    /**
     * Create an instance of {@link Find }
     * 
     */
    public Find createFind() {
        return new Find();
    }

    /**
     * Create an instance of {@link Pager }
     * 
     */
    public Pager createPager() {
        return new Pager();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link AbstractFilter }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "abstractFilter")
    public JAXBElement<AbstractFilter> createAbstractFilter(AbstractFilter value) {
        return new JAXBElement<AbstractFilter>(_AbstractFilter_QNAME, AbstractFilter.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Customer }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "customer")
    public JAXBElement<Customer> createCustomer(Customer value) {
        return new JAXBElement<Customer>(_Customer_QNAME, Customer.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link FindSingleResponse }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "findSingleResponse")
    public JAXBElement<FindSingleResponse> createFindSingleResponse(FindSingleResponse value) {
        return new JAXBElement<FindSingleResponse>(_FindSingleResponse_QNAME, FindSingleResponse.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Create }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "create")
    public JAXBElement<Create> createCreate(Create value) {
        return new JAXBElement<Create>(_Create_QNAME, Create.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Find }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "find")
    public JAXBElement<Find> createFind(Find value) {
        return new JAXBElement<Find>(_Find_QNAME, Find.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link CreateResponse }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "createResponse")
    public JAXBElement<CreateResponse> createCreateResponse(CreateResponse value) {
        return new JAXBElement<CreateResponse>(_CreateResponse_QNAME, CreateResponse.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link FindResponse }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "findResponse")
    public JAXBElement<FindResponse> createFindResponse(FindResponse value) {
        return new JAXBElement<FindResponse>(_FindResponse_QNAME, FindResponse.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link UpdateResponse }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "updateResponse")
    public JAXBElement<UpdateResponse> createUpdateResponse(UpdateResponse value) {
        return new JAXBElement<UpdateResponse>(_UpdateResponse_QNAME, UpdateResponse.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link FindSingle }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "findSingle")
    public JAXBElement<FindSingle> createFindSingle(FindSingle value) {
        return new JAXBElement<FindSingle>(_FindSingle_QNAME, FindSingle.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link CustomerFilter }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "customerFilter")
    public JAXBElement<CustomerFilter> createCustomerFilter(CustomerFilter value) {
        return new JAXBElement<CustomerFilter>(_CustomerFilter_QNAME, CustomerFilter.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Update }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "update")
    public JAXBElement<Update> createUpdate(Update value) {
        return new JAXBElement<Update>(_Update_QNAME, Update.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link AbstractEntity }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://xxxxxxx/", name = "abstractEntity")
    public JAXBElement<AbstractEntity> createAbstractEntity(AbstractEntity value) {
        return new JAXBElement<AbstractEntity>(_AbstractEntity_QNAME, AbstractEntity.class, null, value);
    }

}

The package-info.java class:

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2014.09.12 at 03:44:51 PM CEST 
//

@javax.xml.bind.annotation.XmlSchema(namespace = "http://xxxxxxx/")
package einvoice.proxy.customerdaoservice;

I get error while connecting to my web service:

javax.xml.ws.soap.SOAPFaultException: Unmarshalling Error: unexpected
element (uri:»», local:»OrderID»). Expected elements are
<{}Login>,<{}CrewId>,<{}OrderID >,<{}OrderNumber >

Service is exposed using org.apache.cxf.transport.servlet.CXFServlet and jaxws:endpoint annotation. The client is generated using CXF. Firstly, suprising for me is that I’m using the same technology on both ends and the solution is not working, secondly, this mysterious {} in error messages.

So, what is wrong and how to understand this {}?

asked May 15, 2012 at 12:10

Danubian Sailor's user avatar

Danubian SailorDanubian Sailor

22.3k38 gold badges145 silver badges217 bronze badges

Have you noted space between OrderID and ‘>’? Expected is <{}OrderID > and you send >»OrderID». Check if you don’t have spaces in your element names.

While the above answer from Stepan Vihor helped you get what you needed, let me answer your question of what the «{}» means:

It means that the JAX-B Unmarshaller is expecting your OrderID element to have no namespace, i.e. the namespace uri for that element needs to be equal to «».

See here for a brief intro on XML Namespaces

answered Aug 21, 2012 at 17:57

icyitscold's user avatar

0

Have you noted space between OrderID and ‘>’? Expected is <{}OrderID > and you send "OrderID". Check if you don’t have spaces in your element names.

answered May 15, 2012 at 13:03

Stepan Vihor's user avatar

Stepan VihorStepan Vihor

1,0599 silver badges10 bronze badges

4

@icyitscold, the comment I want to add from my experience is
that you can change the elementFormDefault to «qualified» as
elementFormDefault="qualified"
in xs:schema element. The namespace will be qualified by default.

That’s for the WSDL-first approach, if you use code-first approach, you may consider add the change as

@javax.xml.bind.annotation.XmlSchema(
attributeFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED,
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)

answered Aug 15, 2014 at 20:14

chenrui's user avatar

chenruichenrui

8,2733 gold badges30 silver badges41 bronze badges

I got same error,

javax.xml.ws.soap.SOAPFaultException: Unmarshalling Error: unexpected element (uri:»», local:»country»). Expected elements are <{}seconds>,<{}month>,<{}hour>,<{}year>,<{}minutes>,<{}day>

Then I find on the web service side the response type added a new property ‘country’.

To ignore the new added property, add following propertys in ‘jaxws:client’ setting.

<jaxws:client id="abc"
              serviceClass="someClass"
              address="url">
    <jaxws:properties>
        <entry key="schema-validation-enabled" value="false"/>
        <entry key="set-jaxb-validation-event-handler" value="false"/>
    </jaxws:properties>
</jaxws:client>

answered Jan 25, 2018 at 3:09

Sonic.S.Xiang's user avatar

Sometimes you have to specify the names used in the wsdl (case sensitive):
<{Log}>, <{} CrewId>, <{} OrderID>, <{} OrderNumber>

@XmlElement(name = "CrewId")
protected String crewId;
@XmlElement(name = "OrderID ")
protected String orderID;
@XmlElement(name = "Login")
protected String login;
@XmlElement(name = "OrderNumber")
protected String orderNumber;

answered Sep 21, 2013 at 11:05

Abdelhafid's user avatar

AbdelhafidAbdelhafid

7597 silver badges13 bronze badges

Содержание

  1. Unmarshalling Error: unexpected element (uri:»urn:appdynamics», local:»singularityheader») #531
  2. Comments
  3. I get this error when I call the google adwords api.(AdsSoapClient.php line:149)
  4. My servers runs to AppDynamics and error is relative with it.
  5. I just making soap call like this.
  6. And error throwing in AdsSoapClient.php in line 149
  7. I think Google Servers not accept appdynamics headers
  8. We solved this error.
  9. Footer
  10. Unmarshalling error unexpected element
  11. Answered by:
  12. Question
  13. Unmarshalling Error: unexpected element (uri:»http://ws.iam.activenetwork.com/», local:»username»). Expected elements are ,
  14. Answers

Unmarshalling Error: unexpected element (uri:»urn:appdynamics», local:»singularityheader») #531

I get this error when I call the google adwords api.(AdsSoapClient.php line:149)

My servers runs to AppDynamics and error is relative with it.

The text was updated successfully, but these errors were encountered:

Could you be more specific on what you’re trying to do, such as adding your code snippet here?
The error doesn’t seem to related to the AdWords API though.

I talked with AdWords API Team member Sai Teja on google groups and he said that «Looks like the concern is related to PHP client libraries».

I just making soap call like this.

And error throwing in AdsSoapClient.php in line 149

I think Google Servers not accept appdynamics headers

I’m not familiar with appdynamics, so can’t comment on that.
Did you modify any SOAP headers / body before sending to API servers?
And is it possible to get the SOAP logs?

We solved this error.

The error doesn’t related to Google Api like you said before.
Appdynamics adds a special singularity header on all soap calls to make correlation between appdynamics monitored application. We created a custom backend rule for disable the correlation for Google Api Calls from the UI controller .

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Unmarshalling error unexpected element

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I met a complicated problem when I trying to call the JAVA webservice as shown below:

Unmarshalling Error: unexpected element (uri:»http://ws.iam.activenetwork.com/», local:»username»). Expected elements are ,

And I got the request for the webservice:

The response error is :

soap:Client
Unmarshalling Error: unexpected element (uri:»http://ws.iam.activenetwork.com/», local:»username»). Expected elements are ,

Then I try to test this webservice with SOAPUI,request body as below:

Response without any error:

Could you please help find out the source reason for that? It has been confuesed me for a long time.

Answers

Hi Tom Net ,
According to this case, you need to specify RPC formatting style for apply a SoapRpcMethod attribute to the method in the proxy class calling the applicable Web service method. the remote service requires the message body format by using the RPC binding style respectively.
Click here to refer about How to: Control the Overall SOAP Body Formatting for a Web Service Method.

Источник

We will often need to unmarshal Java objects that do not have JAXB annotations, and we are not permitted to make any changes in the source code. This situation may occur when we are working with legacy code or some client jar for which we do not have source code.

1. Problem when unmarshaling without JAXB annotations

In such a case, if we try to unmarshal Java object to XML directly, then we will get an error like this.

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"employee"). Expected elements are (none)
	at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:726)
	at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
	at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
	at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)

Where Employee.java class is as below. It does not have any JAXB annotation such as @XmlRootElement.

public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;

	//constructors, getters and setters

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department="
				+ department + "]";
	}
}

2. Solution to Unmarshal without JAXB annotations

In absence of @XmlRootElement annotation, JAXB is not able to build JAXBElement instance for Employee object. So that’s where you have to help JAXB to construct it manually.

/**
  * Unmarshal XML data from the specified XML Source by <tt>declaredType</tt> and return the
  * resulting content tree.
  * @param  source       source the XML Source to unmarshal XML data from (providers are
  *               only required to support SAXSource, DOMSource, and StreamSource)
  *
  * @param  declaredType  appropriate JAXB mapped class to hold <tt>source</tt>'s xml root element
  * 
  * @return value        Java content rooted by JAXB Element
  */
public <T> JAXBElement<T> unmarshal( javax.xml.transform.Source source, Class<T> declaredType )
        throws JAXBException;

For example –

JAXBElement<Employee> jaxbElement = (JAXBElement<Employee>) jaxbUnmarshaller
          .unmarshal(new StreamSource(xmlFile), Employee.class);

3. Demo

Now let’s see how this unmarshalling code works.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <department>
        <id>101</id>
        <name>IT</name>
    </department>
    <firstName>Lokesh</firstName>
    <id>1</id>
    <lastName>Gupta</lastName>
</employee>
import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
 
import com.howtodoinjava.demo.model.Employee;
 
public class JaxbExample 
{
  public static void main(String[] args) 
  {
    String fileName = "employee.xml";
 
    jaxbXmlFileToObject(fileName);
  }
 
  private static void jaxbXmlFileToObject(String fileName) 
  {
    File xmlFile = new File(fileName);
    JAXBContext jaxbContext;
    try
    {
      jaxbContext = JAXBContext.newInstance(Employee.class);
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
       
      JAXBElement<Employee> jaxbElement = (JAXBElement<Employee>) jaxbUnmarshaller
          .unmarshal(new StreamSource(xmlFile), Employee.class);
       
      Employee employee = jaxbElement.getValue();
       
      System.out.println(employee);
    }
    catch (JAXBException e) 
    {
      e.printStackTrace();
    }
  }
}

Program Output:

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Drop me your questions in the comments section.

Happy Learning !!

Добрый день,

написал тестовый джоб для передачи данных. джоб выполняется с ошибкой:

Ошибка SOAP сервера:  Unmarshalling Error: unexpected element (uri:»http://company.partner.iqcard.ru/», local:»partners»). Expected elements are <{}partners>

Хотя в файле, узел <partners> присутствует.

<shop xmlns=»http://company.partner.iqcard.ru/» xmlns:xs=»http://www.w3.org/2001/XMLSchema» xmlns:xsi=»http://www.w3.org/2001/XMLSchema-instance»>

   <partners>

       <id>22222222</id>

       <parentId>111111</parentId>

       <name>Управляющий магазином</name>

       <adress>Улица</adress>

       <contactPerson>Управляющий</contactPerson>

       <contactPhone>8916123456789</contactPhone>

       <contactEmail>Email@email.ru</contactEmail>

       <site>www.site.ru</site>

   </partners>

</shop>

Не пойму в чем ошибка. Текст джоба внизу.

ПроксиIQCard   = WSСсылки.IQCard.СоздатьWSПрокси(«http://company.partner.iqcard.ru/», «company», «companyServicePort» );

   МояФабрикаXDTO = WSСсылки.IQCard.ПолучитьWSОпределения().ФабрикаXDTO;

   
   XDTOShop             = ПроксиIQCard.ФабрикаXDTO.Тип(«http://company.partner.iqcard.ru/»,»shop»);

   СписокМагазинов       = ПроксиIQCard.ФабрикаXDTO.Создать(XDTOShop);

   
   XDTOShopRequest       = ПроксиIQCard.ФабрикаXDTO.Тип(«http://company.partner.iqcard.ru/», «ShopRequest»);

   Магазин               = ПроксиIQCard.ФабрикаXDTO.Создать(XDTOShopRequest);

   
   
   Магазин.id              = 22222222;

   Магазин.parentId            = 111111;

   Магазин.name            = «Управляющий магазином»;

   Магазин.adress                = «Улица»;

   Магазин.contactPerson        = «Управляющий»;

   Магазин.contactPhone          = «8916123456789»;

   Магазин.contactEmail        = «Email@email.ru»;

   Магазин.site                = «www.site.ru»;

   
   СписокМагазинов.partners.Добавить(Магазин);

   
   //ЗаписьXML = Новый ЗаписьXML;

   //ЗаписьXML.ОткрытьФайл(«C:data.xml», «UTF-8»);

   //МояФабрикаXDTO.ЗаписатьXML(ЗаписьXML,СписокМагазинов);

   
   ПроксиIQCard.shop(СписокМагазинов);

Having problems with jaxb unmarshalling an xml file

<?xml version=»1.0″ encoding=»UTF-8″?>
<!— edited with XMLSpy v2010 rel. 2 (http://www.altova.com) by Regence Employee (THE REGENCE GROUP) —>
<EnrollmentRequest xmlns:xsi=»http://www.w3.org/2001/XMLSchema-instance» xsi:noNamespaceSchemaLocation=»F:DataNetBeansProjects834Parserdataenrollmentschema.xsd»>
<Enrollments>
<EnrollmentType>NewEnrollment</EnrollmentType>
<SourceName>USRINPUT</SourceName>
<GroupIdentifier>
<GroupId>60004854</GroupId>
<SubGroupID>0001</SubGroupID>
</GroupIdentifier>
<EnrollmentPolicy>
<HoursPerWeekWorked>40</HoursPerWeekWorked>
<Enrollment>
<Event>
<EventType>NEW</EventType>
<EventDate>05/15/2009</EventDate>
<EventEffectiveDate>06/10/2009</EventEffectiveDate>
<EventTerminationDate/>
<BreakInCoverage/>
<QualifyingEvent/>
<Description/>
<Reason/>
</Event>
<Cobra>
<CobraType/>
<QualifyingEvent/>
<CobraEffectiveDate/>
<CertificateLength/>
<CobraTerminationDate/>
</Cobra>
<Person>
<Name>
<FirstName>TEST</FirstName>
<LastName>ENROLLMENT</LastName>
<MiddleName/>
<NameSuffix/>
</Name>
<DateOfBirth>05/05/1976</DateOfBirth>
<Gender>Male</Gender>
<MaritalStatus>Single</MaritalStatus>
<Language>ENGL</Language>
<PersonIdentifier>
<PersonId>555555555</PersonId>
<PersonIdentifierType>SocialSecurityNumber</PersonIdentifierType>
</PersonIdentifier>
<PersonIdentifier>
<PersonId>55555567345</PersonId>
<PersonIdentifierType>MedicareId</PersonIdentifierType>
</PersonIdentifier>
<PriorCoverage>
<CarrierName>Kaiser</CarrierName>
<PolicyHolderID>345545</PolicyHolderID>
<EffectiveDate>01/01/2009</EffectiveDate>
<TerminationDate>01/31/2009</TerminationDate>
<PolicyHolderName>Medical</PolicyHolderName>
</PriorCoverage>
<PriorCoverage>
<CarrierName>Providence</CarrierName>
<PolicyHolderID>23474</PolicyHolderID>
<EffectiveDate>02/01/2009</EffectiveDate>
<TerminationDate>03/31/2009</TerminationDate>
<PolicyHolderName>Medical</PolicyHolderName>
</PriorCoverage>
<ContactInformation>
<AddressDetails>
<ContactType>Home</ContactType>
<Address>
<AliasName>ADDR1</AliasName>
<AddressLine1>56 Test Street</AddressLine1>
<AddressLine2/>
<City>Portland</City>
<County>Multnomah</County>
<State>OR</State>
<ZipCode>97203</ZipCode>
<Country>US</Country>
</Address>
</AddressDetails>
<AddressDetails>
<ContactType>Mailing</ContactType>
<Address>
<AliasName>ADDR1</AliasName>
<AddressLine1>89 Mailing Street</AddressLine1>
<AddressLine2/>
<City>Portland</City>
<County>Multnomah</County>
<State>OR</State>
<ZipCode>97203</ZipCode>
<Country>US</Country>
</Address>
</AddressDetails>
<PhoneNumber>
<ContactType>Home</ContactType>
<PhoneNumber>665-567-8888</PhoneNumber>
</PhoneNumber>
<EMailAddress>
<EmailAddress>user@home.com</EmailAddress>
</EMailAddress>
</ContactInformation>
<Membership>
<MembershipIdentifier>
<MemberID/>
<MemberIdentifierType>CPSS_SBSB_ID</MemberIdentifierType>
</MembershipIdentifier>
<RelationshipToSubscriber>Subscriber</RelationshipToSubscriber>
<MemberIndex>0</MemberIndex>
<InsuranceIDCard>
<IDLevel>FAMILY</IDLevel>
<IDBackground>100</IDBackground>
</InsuranceIDCard>
<Eligibility>
<Coverage>
<ClassId>0001</ClassId>
<Product>
<ProductId>MINN1001</ProductId>
<BusinessCategory>M</BusinessCategory>
</Product>
<Product>
<ProductId>RX000001</ProductId>
<BusinessCategory>R</BusinessCategory>
</Product>
</Coverage>
</Eligibility>
<Preference>
<PreferenceType>EEOB</PreferenceType>
<Detail>
<DetailType>EMAIL</DetailType>
<DetailValue>user@home2.com</DetailValue>
</Detail>
</Preference>
</Membership>
<Medicare>
<Entitlement>Blah</Entitlement>
<EntitlementStartDate>01/01/2008</EntitlementStartDate>
<EntitlementEndDate/>
<MedicareProgram>
<MedicareProgramType>TypeA</MedicareProgramType>
<EffectiveDate>01/01/2008</EffectiveDate>
<TerminationDate/>
</MedicareProgram>
<MedicareProgram>
<MedicareProgramType>TypeB</MedicareProgramType>
<EffectiveDate>01/01/2008</EffectiveDate>
<TerminationDate/>
</MedicareProgram>
</Medicare>
<Disability>
<IsDisabled>false</IsDisabled>
<DisabledDate/>
<Description/>
<VerifiedBy/>
<VerifiedDate/>
<VerificationMethod>EMAIL</VerificationMethod>
</Disability>
</Person>
</Enrollment>
</EnrollmentPolicy>
</Enrollments>
</EnrollmentRequest>

<?xml version=»1.0″ encoding=»UTF-8″?>
<xs:schema xmlns:xs=»http://www.w3.org/2001/XMLSchema» xmlns:tns=»http://dto.sil.regence.com/EnrollmentRequest» xmlns:ns1=»http://dto.sil.regence.com/EnrollmentType» xmlns:ns2=»http://group.dto.sil.regence.com/GroupIdentifier» xmlns:ns3=»http://enrollment.dto.sil.regence.com/EnrollmentPolicy» targetNamespace=»http://dto.sil.regence.com/EnrollmentRequest» version=»1.0″>
<xs:import namespace=»http://dto.sil.regence.com/EnrollmentType» schemaLocation=»EnrollmentType.xsd»/>
<xs:import namespace=»http://group.dto.sil.regence.com/GroupIdentifier» schemaLocation=»group/GroupIdentifier.xsd»/>
<xs:import namespace=»http://enrollment.dto.sil.regence.com/EnrollmentPolicy» schemaLocation=»enrollment/EnrollmentPolicy.xsd»/>
<xs:element name=»EnrollmentRequest»>
<xs:complexType>
<xs:annotation>
<xs:documentation/>
</xs:annotation>
<xs:sequence>
<xs:element name=»Enrollments»>
<xs:complexType>
<xs:sequence>
<xs:element name=»EnrollmentType» type=»ns1:EnrollmentType»/>
<xs:element name=»SourceName» type=»xs:string»/>
<xs:element name=»GroupIdentifier» type=»ns2:GroupIdentifier»/>
<xs:element name=»EnrollmentPolicy» type=»ns3:EnrollmentPolicy»/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

kind of stuck as to why i cant get this xml file to unmarshal

javax.xml.bind.UnmarshalException: unexpected element (uri:»», local:»EnrollmentRequest»). Expected elements are (none)
at

Понравилась статья? Поделить с друзьями:
  • Unmanaged exception 0xc0000005 vegas pro как исправить
  • Unlocking please wait no username error code 63 unlock failed перевод
  • Unlocker error debug privileges
  • Unlock xiaomi error 1004
  • Unlock tool ошибка 0xc0000005