JAVA-JAXB /将类定义为字段

时间:2013-03-19 06:22:20

标签: java jaxb

我正在使用jaxb,据我所知,我们为每个元素和属性字段定义,jaxb重新调整此属性,并将其值放入此元素中。我的问题是我的一个属性是class:

<div class="hello"> Hi </div>

所以我想在类div中定义下一个:

String class;
public String getClass() {
    return class;
}

@XmlAttribute
public void setClass(String class) {
    this.class = class;
}

但我不能因为 - Syntax error on token "class", invalid VariableDeclarator

我该怎么办?

1 个答案:

答案 0 :(得分:3)

您可以使用nameXmlAttribute属性为映射变量指定其他名称。

String className;
public String getClassName() {
    return clazz;
}

@XmlAttribute(name="class")
public void setClassName(String className) {
    this.className = className;
}

工作得非常好

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

public class Test {

    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(Div.class);

        Div div = new Div();
        div.setClassName("new-item");
        StringWriter sw = new StringWriter();
        context.createMarshaller().marshal(div, sw);
        System.out.println(sw.toString());

        String s = "<div class=\"hello\"> Hi </div>";
        Div object = (Div) context.createUnmarshaller().unmarshal(new StringReader(s));
        System.out.println(object.getClassName());

    }

    @XmlType(name = "div")
    @XmlRootElement(name = "div")
    public static class Div {

        private String className;

        @XmlAttribute(name = "class")
        public String getClassName() {
            return className;
        }

        public void setClassName(String className) {
            this.className = className;
        }
    }
}