簡體   English   中英

JaxB解組定制XML

[英]JaxB unmarshal custom xml

我目前正在嘗試將一些現有的XML解組到我手工創建的幾個類中。 問題是,我總是收到一個錯誤消息,告訴我,JaxB期望使用天氣元素,但是找到了天氣元素。 (?)

javax.xml.bind.UnmarshalException:意外元素(uri:“ http://www.aws.com/aws”,本地:“天氣”)。 期望的元素是<{} 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屬性來看到。這是一個不成功的想法。^^)是的,我的確嘗試設置名稱空間,但是設置的是名稱空間的uri而不是...名稱。

我建議您在帶有@XmlSchema批注的域模型中添加一個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;

注意

您的XmlRootElement@XmlElement批注不應包含名稱空間前綴。 您應該使用@XmlRootElement(name = "weather")而不是@XmlRootElement(name = "aws:weather")

欲獲得更多信息

您的代碼中需要名稱空間。 名稱空間前綴是沒有意義的,您需要實際的名稱空間(即“ http://www.aws.com/aws”)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM