gpt4 book ai didi

java - JaxB 解码自定义 xml

转载 作者:行者123 更新时间:2023-11-29 08:05:20 24 4
gpt4 key购买 nike

我目前正在尝试将一些现有的 XML 解码为我手动创建的几个类。问题是,我总是收到一个错误,告诉我,JaxB 需要一个天气元素,但找到了一个天气元素。 (?)

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.aws.com/aws", local:"weather"). Expected elements are <{}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 属性看到这一点。这是一个不成功的想法。^^)是的,我确实尝试设置 namespace ,但设置的是 namespace 的 uri 而不是它的...名称。

最佳答案

我建议在您的域模型中添加一个 package-info 类,并使用 @XmlSchema 注释来指定 namespace 限定:

包信息

@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")

了解更多信息

关于java - JaxB 解码自定义 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11652127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com