2016-09-28 50 views
0

我試圖反序列化在Java中該段XML的:簡單的XML反序列化不同的元素類型具有相同的名稱

<anime id="16986"> 
    <info type="Picture" src="http://~.jpg" width="141" height="200"> 
     <img src="http://~" width="141" height="200"/> 
     <img src="http://~" width="318" height="450"/> 
    </info> 
    <info type="Main title" lang="EN">Long Riders!</info> 
    <info type="Alternative title" lang="JA">ろんぐらいだぁす!</info> 
</anime> 

我遇到的問題是,info元素或者可以有一個內嵌清單img的或它可以只包含文本。我在考慮在我的AnimeHolder類中將info作爲@Element,但我不能有重複的註釋。我還想訪問info的lang屬性來檢查它是EN還是JP。

我使用這些類來反序列化的數據:

@Root(name="anime", strict=false) 
public class AnimeHolder { 

    @Attribute(name="id") 
    private String ANNID; 

    @ElementList(inline=true) 
    private List<InfoHolder> infoList; 

    public String getANNID() { 
     return ANNID; 
    } 

    public List<InfoHolder> getInfoList() { 
     return infoList; 
    } 
} 

,併爲信息項目:

@Root(name="info", strict = false) 
public class InfoHolder { 

    @ElementList(inline=true, required = false) 
    private List<ImgHolder> imgList; 

    @Attribute(name = "lang", required = false) 
    private String language; 

    public List<ImgHolder> getImgList() { 
     return imgList; 
    } 
} 
+1

您可能需要將「」定義爲具有「混合」內容,並在代碼中處理文本與「」元素,例如,禁止同時使用文字和「」。請參閱「[如何使用MixedContent數據處理JAXB ComplexType?](http://stackoverflow.com/q/12568247/5221149)」。 – Andreas

+0

謝謝!這表明我朝着正確的方向前進。發佈我的解決方案。 –

回答

0

安德烈亞斯我發現我需要尋找到處理混合內容。做一些搜索引導我到這solution關於創建自定義Converter。在寫完自己的電子郵件後發現它沒有被調用,this幫助解決了它。這裏是我重新工作InfoHolder類和轉換器:

@Root(name="info", strict = false) 
@Convert(InfoHolder.InfoConverter.class) 
public class InfoHolder { 

    private String englishTitle; 
    private String imageURL; 

    static class InfoConverter implements Converter<InfoHolder> { 
     @Override 
     public InfoHolder read(InputNode node) throws Exception { 
      String value = node.getValue(); 
      InfoHolder infoHolder = new InfoHolder(); 

      if (value == null){ 
       InputNode nextNode = node.getNext(); 
       while (nextNode != null){ 
        String tag = nextNode.getName(); 

        if (tag.equals("img") && nextNode.getAttribute("src") != null){ 
         infoHolder.imageURL = nextNode.getAttribute("src").getValue(); 
        } 
        nextNode= node.getNext(); 
       } 
      } else { 
       while (node != null){ 
        if (node.getAttribute("lang") != null){ 
         if (node.getAttribute("lang").getValue().equals("EN")){ 
          infoHolder.englishTitle = value; 
          break; 
         } 
        } 
        node = node.getNext(); 
       } 
      } 

      return infoHolder; 
     } 

     @Override 
     public void write(OutputNode node, InfoHolder value) throws Exception { 

     } 
    } 
} 

我還需要有一個Serializer一個SimpleXmlConverterFactory使用AnnotationStrategy像這樣實例:

SimpleXmlConverterFactory factory = SimpleXmlConverterFactory.create(new Persister(new AnnotationStrategy())); 

使用自定義轉換器暴露了XML節點,允許我確定info節點是否有img子節點,如果沒有,請自己獲取節點值。

相關問題