使用JAXB自定义对象/元素名称 [英] Customize object/element name with JAXB

查看:87
本文介绍了使用JAXB自定义对象/元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JAXB的新手,所以我很难破解这个(我认为)非常简单的用例.

I'm very new to JAXB, so I'm having trouble cracking this (I assume) very simple use case.

我有一套模式.我无法控制它们,我无法更改它们.在这些模式中,我有诸如

I have a set of schemas I got. I have no control over those, I cannot change them. In these schemas, I have declarations such as

<xs:complexType name="CustomerType">
    ...

我尝试从这些生成类.所以这样的声明变成

I try to generate classes from these. So such a declaration becomes

@XmlType(name = "CustomerType", propOrder = {
    "field1",
    "field2"
})
public class CustomerType {
    ...

然后,我需要使用此类使用RestTemplate创建XML消息.问题是,XML消息中的对象不应为"CustomerType",而应仅为"Customer".就像我说的那样,我无法编辑架构.我也不能直接编辑生成的源.我需要某种外部定制,以告诉源生成过程或编组过程如何转换对象的名称.任何建议将不胜感激.

Then I need to use this class to create XML messages using a RestTemplate. The problem is, the object in the XML message is not supposed to be "CustomerType", it's supposed to be just "Customer". Like I said, I cannot edit the schemas. I also cannot directly edit the generated sources. I need some kind of external customization that tells either the source generating process, or the marshalling process, how to transform the names of the objects. Any advice will be greatly appreciated.

推荐答案

您可以使用绑定来自定义类或属性名称.通常,您会有一个像 bindings.xjb 这样的文件:

You can use bindings to customize class or property names. Typically you'll have a file like bindings.xjb like this:

<jaxb:bindings version="1.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc">

    <jaxb:bindings schemaLocation="schema.xsd" node="/xsd:schema">
        <jaxb:bindings node="xsd:customType[@name='CustomerType']">
            <jaxb:class name="Customer"/>
        </jaxb:bindings>
        <jaxb:bindings node="xsd:customType[@name='CustomerType']//xsd:element[@name='field1']">
            <jaxb:property name="f1"/>
        </jaxb:bindings>
    </jaxb:bindings>
</jaxb:bindings>

您可以通过绑定自定义很多东西(请参见),但当然不是全部.

There are quite a few things you can customize with bindings (see this), but certainly not everything.

这篇关于使用JAXB自定义对象/元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆