JAXB - 将相同的属性添加到不同的元素

时间:2017-03-17 11:59:24

标签: java xml jaxb moxy

我仔细研究了讨论"JAXB Adding attributes...",并希望进一步发展。

例如,有以下类:

@XmlRootElement(name = "company")
@XmlType(propOrder = {"id", "name", "address"})
public class Company {

    private String id;
    private String name;
    private String address;

    @XmlElement(name = "id")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement(name = "address")
    public String getAddress() {
        return name;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

在编组了一个对象后,我们有了:

<company>
    <id>1</id>
    <name>Abc</name>
    <address>Mountain View, United States</address>
</company>

是否有一个优雅的解决方案,例如使用注释@XmlPaths@XmlPath@XmlElements@XmlElement, - 作为结果接收:

<company>
    <id>1</id>
    <name lang="en">Abc</name>
    <address lang="en">Mountain View, United States</address>
</company>

1 个答案:

答案 0 :(得分:1)

如何使用lang属性创建自定义String并使用它而不是字符串

例如:

public class LangString {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "lang")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "language")
    protected String lang;

    //GETTERS & SETTERS
}

您的代码:

@XmlRootElement(name = "company")
@XmlType(propOrder = {"id", "name", "address"})
public class Company {

    private String id;
    private LangString name;
    private LangString address;

    @XmlElement(name = "id")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @XmlElement(name = "name")
    public LangString getName() {
        return name;
    }

    public void setName(LangString name) {
        this.name = name;
    }

    @XmlElement(name = "address")
    public LangString getAddress() {
        return name;
    }

    public void setAddress(LangString address) {
        this.address = address;
    }
}

上面的代码是从我的应用程序的xsd架构生成的,该架构包含具有lang属性的元素,因此@XmlSchemaType

希望有所帮助