2010-11-25 42 views
4

我有一個XML,它無法控制它的生成方式。我想通過將它解組爲一個由我手寫的類來創建一個對象。其結構具有「未知」名稱的JAXB映射元素

一個片段是這樣的:

<categories> 
    <key_0>aaa</key_0> 
    <key_1>bbb</key_1> 
    <key_2>ccc</key_2> 
</categories> 

我該如何處理這種情況?當然元素數是可變的。

+0

是否XML結構有一個良好定義的模式? – 2010-11-25 15:44:41

+0

否。源代碼是一些PHP REST Web服務(並不意味着它無法完成)。 – bbcooper 2010-11-25 18:14:00

回答

5

如果您使用下面的對象模型,然後每個未映射KEY_#元素將被保存爲org.w3c.dom.Element中的一個實例:

import java.util.List; 
import javax.xml.bind.annotation.XmlAnyElement; 
import javax.xml.bind.annotation.XmlRootElement; 
import org.w3c.dom.Element; 

@XmlRootElement 
public class Categories { 

    private List<Element> keys; 

    @XmlAnyElement 
    public List<Element> getKeys() { 
     return keys; 
    } 

    public void setKeys(List<Element> keys) { 
     this.keys = keys; 
    } 

} 

如果任何元素對應於使用@XmlRootElement批註映射的類,則可以使用@XmlAnyElement(lax = true),並且已知元素將轉換爲相應的對象。舉一個例子,請參閱:

0

對於這個簡單的元素,我想創建一個類稱爲類別:

import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 
public class Categories { 

    protected String key_0; 
    protected String key_1; 
    protected String key_2; 

    public String getKey_0() { 
     return key_0; 
    } 

    public void setKey_0(String key_0) { 
     this.key_0 = key_0; 
    } 

    public String getKey_1() { 
     return key_1; 
    } 

    public void setKey_1(String key_1) { 
     this.key_1 = key_1; 
    } 

    public String getKey_2() { 
     return key_2; 
    } 

    public void setKey_2(String key_2) { 
     this.key_2 = key_2; 
    } 

} 

然後在主法等方法,我會創建解組:

JAXBContext context = JAXBContext.newInstance(Categories.class); 
Unmarshaller um = context.createUnmarshaller(); 
Categories response = (Categories) um.unmarshal(new FileReader("my.xml")); 
// access the Categories object "response" 

爲了能夠檢索所有對象,我想我會把一個根元素中的所有元素放在一個新的xml文件中,並用@XmlRootElement註釋爲這個根元素編寫一個類。

希望幫助, MMAN

+0

+1,但是您不需要在XmlRootElement上指定名稱,因爲它將默認爲「類別」,您也不需要使用@XmlElement進行註釋,因爲它是默認值。 – 2010-11-25 15:56:04

0

使用這樣

 @XmlRootElement 
     @XmlAccessorType(XmlAccessType.FIELD) 
     public static class Categories { 


      @XmlAnyElement 
      @XmlJavaTypeAdapter(ValueAdapter.class) 
      protected List<String> categories=new ArrayList<String>(); 

      public List<String> getCategories() { 
       return categories; 
      } 
      public void setCategories(String value) { 
       this.categories.add(value); 
      } 
     } 

     class ValueAdapter extends XmlAdapter<Object, String>{ 

      @Override 
      public Object marshal(String v) throws Exception { 
       // write code for marshall 
      return null; 
      } 

      @Override 
      public String unmarshal(Object v) throws Exception { 
       Element element = (Element) v; 
       return element.getTextContent(); 
      } 
     } 
相關問題