EclipseLink MOXy @XmlPath支持具有不同值的元素,例如<pty id =“ID1”src =“6”r =“1”> </pty>

时间:2012-08-15 06:50:38

标签: eclipselink moxy

有人可以帮助我使用

生成<Pty ID="ID1" Src="6" R="1">代码 单个注释中的EclipseLink MOXy @XmlPath

提前多多感谢。

1 个答案:

答案 0 :(得分:0)

我不确定我的要求是否正确,但这是我认为你想要做的答案。

<强> IdAdapter

您可以编写XmlAdapter来将单个id值转换为具有多个属性的对象。这些其他属性将使用默认值设置。

package forum11965153;

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

public class IdAdapter extends XmlAdapter<IdAdapter.AdaptedId, String> {

    public static class AdaptedId {
        @XmlAttribute(name="ID") public String id;
        @XmlAttribute(name="Src") public String src = "6";
        @XmlAttribute(name="R") public String r = "1";
    }

    @Override
    public AdaptedId marshal(String string) throws Exception {
        AdaptedId adaptedId = new AdaptedId();
        adaptedId.id = string;
        return adaptedId;
    }

    @Override
    public String unmarshal(AdaptedId adaptedId) throws Exception {
        return adaptedId.id;
    }
}

<强>控股

@XmlJavaTypeAdapter注释用于指定XmlAdapter。要将值折叠到根元素中,请使用MOXy的@XmlPath(".")注释(请参阅:http://blog.bdoughan.com/2010/07/xpath-based-mapping.html)。

package forum11965153;

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

import org.eclipse.persistence.oxm.annotations.XmlPath;

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

    @XmlJavaTypeAdapter(IdAdapter.class)
    @XmlPath(".")
    String id;

}

<强> jaxb.properties

如您所知,要将MOXy指定为JAXB提供程序,您需要在与域模型相同的程序包中包含名为jaxb.properties的文件,并带有以下条目(请参阅:http://blog.bdoughan.com/search/label/jaxb.properties

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

<强>演示

以下演示代码可用于证明一切正常:

package forum11965153;

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

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StringReader xml = new StringReader("<Pty ID='ID1' Src='6' R='1'/>");
        Pty pty = (Pty) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(pty, System.out);
    }

}

<强>输出

以下是运行演示代码的输出:

<?xml version="1.0" encoding="UTF-8"?>
<Pty ID="ID1" Src="6" R="1"/>
相关问题