简体   繁体   English

如何使用JAXB将子元素属性绑定到字段?

[英]How to bind child element attributes to fields with JAXB?

Given the following XML 给出以下XML

<mappings>
  <map>
     <source srcAttr="oof">foo</source>
     <target trgAttr="rab">bar</target>
  </map>
  <map>
    ...

Is it possible with JAXB to unmarshal the <map> elements into a single class Map containing values and attributes of <source> and <target> ? 是否可以使用JAXB将<map>元素解组为包含<source><target>属性的单个类Map

@XmlRootElement
class Map {

   @XmlElement
   String source;

   @???
   String srcAttr;

   @XmlElement
   String target;

   @???
   String trgAttr;
}

I don't want to create extra classes for Source and target. 我不想为Source和target创建额外的类。

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group. 注意:我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JSR-222)专家组的成员。

You could use MOXy's @XmlPath extension to handle this use case: 您可以使用MOXy的@XmlPath扩展来处理此用例:

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Map {

   String source;

   @XmlPath("source/@srcAttr")
   String srcAttr;

   String target;

   @XmlPath("target/@trgAttr")
   String trgAttr;

}

For More Information 欲获得更多信息

Yes! 是! Just replace ??? 只需更换??? with @XmlAttribute annotaion. 使用@XmlAttribute annotaion。

Also this might be helpful jaxb example and this oracle examples 这也许有助于jaxb示例和这个oracle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM