You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JAXB/MOXy绑定作为XML属性存在的@XmlIDREF?

问题原因

你当前的写法是将ID值作为<SomeAttribute>的文本内容输出,和你需要的idref属性结构不符,@XmlPath不生效大概率是注解空格错误、或者没有正确启用MOXy实现导致的。

正确实现步骤

1. 基础配置前置要求

首先确保SomeOtherClass的主键字段已添加@XmlID注解,这是IDREF绑定的必要前提:

import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlID;

@XmlRootElement(name = "SomeOtherClass")
public class SomeOtherClass {
    @XmlID
    @XmlAttribute
    protected String id;

    // 补全getter、setter方法
}

2. 修正MyClass的属性注解

删除错误的@XmlElement注解,修正@XmlPath的多余空格,写法如下:

import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlIDREF;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name = "MyClass")
public class MyClass {
    @XmlAttribute
    protected String id;

    @XmlIDREF
    @XmlPath("SomeAttribute/@idref")
    protected SomeOtherClass someAttribute;

    // 补全getter、setter方法
}

3. 确认启用MOXy JAXB实现

默认JDK内置的JAXB实现不支持@XmlPath注解,需要手动启用MOXy:
在你的模型类所在的类路径下新增jaxb.properties文件,内容为:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

原生JAXB兼容方案(无需MOXy)

如果不使用MOXy的扩展注解,可以通过封装包装类实现:

  1. 定义属性包装类
public class SomeAttribute {
    @XmlAttribute(name = "idref")
    @XmlIDREF
    public SomeOtherClass value;
}
  1. 调整MyClass的属性映射
@XmlElement(name = "SomeAttribute")
protected SomeAttribute someAttribute;

内容的提问来源于stack exchange,提问作者Carsten Zerbst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:18:05