首页 文章

JaxB unmarshal自定义xml

提问于
浏览
1

我目前正在尝试将一些现有的XML解组为我手工创建的几个类 . 问题是,我总是得到一个错误,告诉我,JaxB期望一个天气元素,但找到一个天气元素 . (?)

javax.xml.bind.UnmarshalException:意外元素(uri:“http://www.aws.com/aws”,local:“weather”) . 预期元素为<{} api>,<{} location>,<{} weather>

我在元素名称中尝试使用和不使用“aws:” .

这是我的天气等级:

@XmlRootElement(name = "aws:weather")
public class WeatherBugWeather
{
    private WeatherBugApi api;
    private List<WeatherBugLocation> locations;
    private String uri;

    @XmlElement(name="aws:api")
    public WeatherBugApi getApi()
    {
        return this.api;
    }

    @XmlElementWrapper(name = "aws:locations")
    @XmlElement(name = "aws:location")
    public List<WeatherBugLocation> getLocations()
    {
        return this.locations;
    }

    public void setApi(WeatherBugApi api)
    {
        this.api = api;
    }

    public void setLocations(List<WeatherBugLocation> locations)
    {
        this.locations = locations;
    }

    @XmlAttribute(name="xmlns:aws")
    public String getUri()
    {
        return this.uri;
    }

    public void setUri(String uri)
    {
        this.uri = uri;
    }
}

这就是我尝试解析的XML:

<?xml version="1.0" encoding="utf-8"?>
<aws:weather xmlns:aws="http://www.aws.com/aws">
    <aws:api version="2.0" />
    <aws:locations>
        <aws:location cityname="Jena" statename="" countryname="Germany" zipcode="" citycode="59047" citytype="1" />
    </aws:locations>
</aws:weather>

我不太确定我做错了什么 . 任何提示?我怀疑问题是xmlns定义,但我不知道如何处理它 . (你可以通过查看uri-property来看到 . 这是一个不成功的想法 . ^^)是的,我确实尝试设置命名空间,而是设置命名空间的uri而不是它的... name .

2 回答

  • 2

    您需要在代码中使用命名空间 . 名称空间前缀毫无意义,您需要实际的名称空间(即"http://www.aws.com/aws") .

    @XmlRootElement(name = "weather", namespace="http://www.aws.com/aws")
    
  • 2

    我建议在您的域模型中添加一个带有 @XmlSchema 注释的 package-info 类来指定命名空间限定:

    package-info

    @XmlSchema(
        namespace = "http://www.aws.com/aws",
        elementFormDefault = XmlNsForm.QUALIFIED)
    package com.example.foo;
    
    import javax.xml.bind.annotation.XmlNsForm;
    import javax.xml.bind.annotation.XmlSchema;
    

    Note

    您的 XmlRootElement@XmlElement 注释不应包含名称空间前缀 . 你应该 @XmlRootElement(name = "weather") 而不是 @XmlRootElement(name = "aws:weather")

    For More Information

相关问题