JAXB-将@xmlvalue与令牌字段一起使用



这似乎是一个基本问题,但我无法在其他地方找到答案。如果是重复的帖子,请原谅我。

是否可以在标记为@xmlaccessortype(xmlaccesstype.field)的类上具有@xmlvalue注释?

我试图用JAXB解析XML文件,而XML本身很大并且具有其他字段,但问题是该字段的特定于此:

<root>
  ...
  <holiday holidayId="9">Christmas</holiday>
  ...
</root>

映射是:

public class Holiday extends Model {
    @XmlAttribute(name="holidayId")
    private String holidayId;
    @XmlValue
    private String holiday;
}

该字段被声明为XML中的令牌类型。

@xmlvalue注释正在给我一个IllegalantationException(如果我评论@xmlvalue和假日领域,则映射正常工作)。为什么失败?什么是工作?请建议。

是的,它应该没有问题。我使用了这些类:

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
    @XmlElement(name = "holiday")
    List<Holiday> holidays;
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Holiday {
    @XmlAttribute(name="holidayId")
    private String holidayId;
    @XmlValue
    private String holiday;
}

对我来说,它运行良好。我将您的XML示例输入与此测试代码一起使用:

JAXBContext context = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File file = new File("root.xml");
Root root = (Root) unmarshaller.unmarshal(file);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);

相关内容

最新更新