使用JAXB标记属性的编组/解组字段

时间:2012-10-16 12:09:30

标签: java xml xpath jaxb

假设我有课程示例:

class Example{
  String myField;
}

我想以这种方式解组它:

<Example>
  <myField value="someValue" />
</Example>

是否可以使用JAXB XJC以这种方式解组对象? (我在EclipseLink中了解XmlPath,但不能使用它。)

2 个答案:

答案 0 :(得分:3)

您可以针对此用例使用XmlAdapter。在XmlAdapter中,您将String转换为具有映射到XML属性的一个属性的对象。

<强> XmlAdapter

package forum12914382;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MyFieldAdapter extends XmlAdapter<MyFieldAdapter.AdaptedMyField, String> {

    @Override
    public String unmarshal(AdaptedMyField v) throws Exception {
        return v.value;
    }

    @Override
    public AdaptedMyField marshal(String v) throws Exception {
        AdaptedMyField amf = new AdaptedMyField();
        amf.value = v;
        return amf;
    }

    public static class AdaptedMyField {

        @XmlAttribute
        public String value;

    }

}

示例

package forum12914382;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name="Example")
@XmlAccessorType(XmlAccessType.FIELD)
class Example{

    @XmlJavaTypeAdapter(MyFieldAdapter.class)
    String myField;

}

<强>演示

package forum12914382;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum12914382/input.xml");
        Example example = (Example) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(example, System.out);
    }

}

<强> input.xml中/输出

<Example>
  <myField value="someValue" />
</Example>

相关示例

答案 1 :(得分:0)

是的,手动添加@XmlAttribute - 注释或从XSD生成类。