2016-09-28 53 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子节点,如果没有,请自己获取节点值。

相关问题