简体   繁体   English

JAXB:具有文本内容和属性的元素,使用XJC生成类

[英]JAXB: an element with textual content and attributes, generating classes with XJC

Recently I have faced a problem which seems to be very common: how to represent an XML element with attributes and simple textual content, like this: 最近我遇到了一个似乎很常见的问题:如何用属性和简单的文本内容来表示XML元素,如下所示:

<elem attr="aval">elemval</elem>

using JAXB. 使用JAXB。

I've found many advices on how to do this, but every one of these advices involves manual editing of binding classes. 我已经找到了很多关于如何做到这一点的建议,但是这些建议中的每一个都涉及手动编辑绑定类。

I have a set of schemas and I use XJC to convert these schemas to Java classes. 我有一组模式,我使用XJC将这些模式转换为Java类。 However, it seems that it produces wrong code, ie it does not generate methods to set plain content, there are methods for setting attributes only. 但是,它似乎产生错误的代码,即它不生成设置普通内容的方法,只有设置属性的方法。

Is it possible to fix this behavior of XJC? 是否有可能解决XJC的这种行为? Extensive googling didn't help on this question. 广泛的谷歌搜索对这个问题没有帮助。

Below is an XML schema that defines the XML structure for you use case. 下面是一个XML模式,它为您的用例定义XML结构。

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/schema"
    xmlns:tns="http://www.example.org/schema" elementFormDefault="qualified">

    <element name="elem">
        <complexType>
            <simpleContent>
                <extension base="string">
                    <attribute name="attr" type="string" />
                </extension>
            </simpleContent>
        </complexType>
    </element>

</schema>

Generating a JAXB model from this XML schema will result in the following class: 从此XML架构生成JAXB模型将生成以下类:

package forum12859885;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "value"
})
@XmlRootElement(name = "elem")
public class Elem {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "attr")
    protected String attr;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getAttr() {
        return attr;
    }

    public void setAttr(String value) {
        this.attr = value;
    }

}

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

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