javax.xml.bind.UnmarshalException

dreambigcoder picture dreambigcoder · Apr 1, 2013 · Viewed 29.9k times · Source

I am getting the following error:

javax.xml.bind.UnmarshalException: unexpected element(uri:"http://www.docsite.com/ClientConfig.xsd", local:"ClientConfig").
Expected elements are <{http://www.docsite.com/ClientConfig.xsd/}ClientConfig>

my root element class file is:

@XmlRootElement(name="ClientConfig",namespace="http://www.docsite.com/ClientConfig.xsd/")
public class ClientConfig {}

my package.info file is:

@XmlSchema(namespace="http://www.docsite.com/ClientConfig.xsd",elementFormDefault=XmlNsForm.QUALIFIED)

package com.convertXml.docSite.XmlConverter;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlNsForm;

let me know what can I do to fix this

Answer

bdoughan picture bdoughan · Apr 1, 2013

TL;DR

You have an extra / at the end of the namespace specified in the @XmlRootElement annotation.


LONG ANSWER

package-info

The namespace is specified correctly in the package level @XmlSchema annotation:

@XmlSchema(namespace="http://www.docsite.com/ClientConfig.xsd",elementFormDefault=XmlNsForm.QUALIFIED)
package com.convertXml.docSite.XmlConverter;

import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlNsForm;

ClientConfig

But you have overridden it with an incorrect namespace on the ClientConfig class. You have an extra / at the end of the namespace specified in the @XmlRooElement annotation.

package com.convertXml.docSite.XmlConverter;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="ClientConfig",namespace="http://www.docsite.com/ClientConfig.xsd/")
public class ClientConfig {}

Since you declared the namespace on the @XmlSchema on the package-info class you don't need to repeat it on the @XmlRootElement.

package com.convertXml.docSite.XmlConverter;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="ClientConfig")
public class ClientConfig {}

Demo

Now the unmarshal will work correctly:

package com.convertXml.docSite.XmlConverter;

import java.io.StringReader;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(ClientConfig.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StringReader xml = new StringReader("<ClientConfig xmlns='http://www.docsite.com/ClientConfig.xsd'/>");
        ClientConfig clientConfig = (ClientConfig) unmarshaller.unmarshal(xml);
    }

}

For More Information