有人可以帮助我使用 <Pty ID="ID1" Src="6" R="1">
标签生成
EclipseLink MOXy @XmlPath
在单个注释中。
提前非常感谢。
我不确定我的要求是否正确,但这是我认为您要做的事情的答案。
身份适配器
您可以编写一个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"/>