2013-04-27 68 views
1
@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。我怎樣才能做到這一點?我想插入子元素在xml樹使用Java的子元素

如何爲這些子元素插入屬性值?我有另一個類叫做MarshDemo,其中創建了一個對象Dekkey,然後setkeyVal()函數通過將值傳遞給函數來調用。

輸出看起來是這樣的:

<Dekkey keyVal="xer"> 
    <kek1 keyVal="biv"> 
     <userkey keyVal="wed"> 
     </userkey> 
    </kek1> 
</Dekkey> 
+0

查覈在的EclipseLink JAXB(MOXY)的@XmlPath延伸:blog.bdoughan.com/2010 /07/xpath-based-mapping.html。在你的例子中,XML文檔中的3個值'xer','biv'和'wed'與你的'Dekkey'類中的2個屬性有什麼關係? – 2013-04-27 10:08:17

回答

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

注:我是EclipseLink JAXB (MOXy)鉛和JAXB (JSR-222)專家小組的成員。

Dekkey

下面是你如何能使用莫西的@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

要指定莫西作爲JAXB你需要包括在同一個包中的以下項域模型稱爲jaxb.properties文件(JSR-222)提供(見:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。

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>