2012-03-21 212 views
2

我有類似於XML:JAXB元素映射

<alpha> 
      <beta> 
        <theta>abcd</theta> 
      </beta> 
    </alpha> 

我想將theta元素的類映射到一個屬性thetaValue爲myBean

@XmlRootElement(name = "alpha") 
public class MyBean { 
    private String thetaValue; 

    public String getThetaValue() { 
     return this.thetaValue; 
    } 

    public void setThetaValue(String thetaValue) { 
     this.thetaValue= thetaValue; 
    } 
} 

有什麼辦法,我可以做到這一點?我使用的是帶有JDK 1.6

回答

4

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


使用任何JAXB(JSR-222)執行

使用任何JAXB(JSR-222)實現,你可以使用一個XmlAdapter映射這個用例。

ThetaValueAdapter

package forum9799081; 

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

public class ThetaValueAdapter extends XmlAdapter<ThetaValueAdapter.Beta, String> { 

    @Override 
    public Beta marshal(String string) throws Exception { 
     Beta beta = new Beta(); 
     beta.theta = string; 
     return beta; 
    } 

    @Override 
    public String unmarshal(Beta beta) throws Exception { 
     return beta.theta; 
    } 

    public static class Beta { 
     public String theta; 
    } 

} 

爲myBean

package forum9799081; 

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

@XmlRootElement(name = "alpha") 
public class MyBean { 
    private String thetaValue; 

    @XmlElement(name="beta") 
    @XmlJavaTypeAdapter(ThetaValueAdapter.class) 
    public String getThetaValue() { 
     return this.thetaValue; 
    } 

    public void setThetaValue(String thetaValue) { 
     this.thetaValue = thetaValue; 
    } 

} 

演示

package forum9799081; 

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

public class Demo { 

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

     File xml = new File("src/forum9799081/input.xml"); 
     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     MyBean myBean = (MyBean) unmarshaller.unmarshal(xml); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(myBean, System.out); 
    } 

} 

的input.xml /輸出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<alpha> 
    <beta> 
     <theta>abcd</theta> 
    </beta> 
</alpha> 

使用的EclipseLink JAXB(莫西)

使用莫西您可以使用@XmlPath擴展來實現相同的映射:

package forum9799081; 

import javax.xml.bind.annotation.*; 
import org.eclipse.persistence.oxm.annotations.XmlPath; 

@XmlRootElement(name = "alpha") 
public class MyBean { 
    private String thetaValue; 

    @XmlPath("beta/theta/text()") 
    public String getThetaValue() { 
     return this.thetaValue; 
    } 

    public void setThetaValue(String thetaValue) { 
     this.thetaValue = thetaValue; 
    } 

} 

更多信息

+1

非常感謝你 – user1282545 2012-03-21 10:46:54