【问题标题】:javax.xml.bind.UnmarshalExceptionjavax.xml.bind.UnmarshalException
【发布时间】:2013-04-01 20:49:31
【问题描述】:

我收到以下错误:

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>

我的根元素类文件是:

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

我的 package.info 文件是:

@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;

让我知道我能做些什么来解决这个问题

【问题讨论】:

    标签: xml namespaces jaxb unmarshalling


    【解决方案1】:

    TL;DR

    @XmlRootElement 注释中指定的命名空间末尾有一个额外的 /。


    长答案

    包裹信息

    在包级别@XmlSchema注解中正确指定了命名空间:

    @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 类上使用不正确的命名空间覆盖了它。在 @XmlRooElement 注释中指定的命名空间末尾有一个额外的 /

    package com.convertXml.docSite.XmlConverter;
    
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name="ClientConfig",namespace="http://www.docsite.com/ClientConfig.xsd/")
    public class ClientConfig {}
    

    由于您在 package-info 类的 @XmlSchema 上声明了命名空间,因此您无需在 @XmlRootElement 上重复它。

    package com.convertXml.docSite.XmlConverter;
    
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name="ClientConfig")
    public class ClientConfig {}
    

    演示

    现在unmarshal 可以正常工作了:

    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);
        }
    
    }
    

    更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2014-06-08
      • 2012-08-30
      • 2017-12-31
      • 2014-09-29
      • 1970-01-01
      • 2013-12-03
      相关资源
      最近更新 更多