1

假设我有课示例:

class Example{
  String myField;
}

我想以这种方式解组它:

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

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

4

2 回答 2

3

你可以利用XmlAdapter这个用例。在这种情况下,XmlAdapter您将转换String为/从具有映射到 XML 属性的一个属性的对象。

xml适配器

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);
    }

}

输入.xml/输出

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

相关示例

于 2012-10-16T12:30:04.777 回答
0

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

于 2012-10-16T12:27:08.197 回答