@XmlRootElement
public class Dekkey {
String keyVal;
String kek1;
public String getKek1() {
return kek1;
}
@XmlElement
public void setKek1(String kek1) {
this.kek1 = kek1;
}
public String getKeyval() {
return keyVal;
}
@XmlAttribute
public void setKeyval(String inpKey) {
this.keyVal = inpKey;
}
}
这是我的代码片段,我想在其中插入一个名为userkey的子元素到子元素kek1。我怎么能这样做?
如何为这些子元素插入属性值?我有另一个名为MarshDemo
的类,其中创建了Dekkey
的对象,然后通过将值传递给函数来调用setkeyVal()
函数。
输出如下:
<Dekkey keyVal="xer">
<kek1 keyVal="biv">
<userkey keyVal="wed">
</userkey>
</kek1>
</Dekkey>
答案 0 :(得分:0)
为简洁起见,我省略了getter和setter,这就是你应该看起来的样子。
@XmlRootElement
public class Dekkey {
@XmlAttribute
String keyVal;
Kek1 kek1;
}
@XmlElement(name="kek1")
public class Kek1 {
@XmlAttribute
String keyVal;
UserKey userkey;
}
@XmlElement(name="userkey")
public class UserKey {
@XmlAttribute
String keyVal;
}
答案 1 :(得分:0)
注意:我是EclipseLink JAXB (MOXy)主管,是JAXB (JSR-222)专家组的成员。
<强> Dekkey 强>
以下是使用MOXy @XmlPath
扩展程序映射用例的方法(请参阅:http://blog.bdoughan.com/2010/07/xpath-based-mapping.html)。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement(name="Dekkey")
@XmlAccessorType(XmlAccessType.FIELD)
public class Dekkey {
@XmlAttribute
String keyVal;
@XmlPath("kek1/@keyVal")
String kek1;
@XmlPath("kek1/userkey/@keyVal")
String userKey;
}
<强> jaxb.properties 强>
要将MOXy指定为JAXB(JSR-222)提供程序,您需要在与域模型相同的包中包含名为jaxb.properties
的文件,并带有以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。< / p>
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
<强>演示强>
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Dekkey.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum16248263/input.xml");
Dekkey dekkey = (Dekkey) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(dekkey, System.out);
}
}
<强> input.xml中/输出强>
<?xml version="1.0" encoding="UTF-8"?>
<Dekkey keyVal="xer">
<kek1 keyVal="biv">
<userkey keyVal="wed"/>
</kek1>
</Dekkey>