XSTREAM - 类强制转换异常

时间:2015-03-09 11:17:29

标签: java xml xstream

我有一个容易理解的难题(对我而言)。

我有一个像这样的XML文件:

    <class name='package.AnnotatedClass2'>
      <attribute name='field1'>
        <attributes>
          <attribute name='targetField1name' />
          <attribute name='targetField2name' />
        </attributes>
      </attribute>
   </class>

我有另一个包含&#34;属性的bean#34;标记(但不存在于XML文件中),全局节点:

<class name="package.Example">
    <global>
        <excluded>
           <attribute name ="field3"/>
        </excluded>
    </global>
  </class>

保留<class>代码

的XmlClass
public class XmlClass {

    /** global configuration */
    public XmlGlobal global;
    /** list of attributes node */
    @XStreamImplicit(itemFieldName="attribute")
    public List<XmlAttribute> attributes;
}

保留<global>代码

的XmlGlobal
public class XmlGlobal {
   public List<XmlTargetExcludedAttribute> excluded;
}

@XStreamAlias("attribute")
public class XmlTargetExcludedAttribute {
   /** name attribute of class node */
   @XStreamAsAttribute
   public String name;
}

和XmlAttribute:

public class XmlAttribute {

   /** list of target attributes */
    public List<XmlTargetAttribute> attributes;
}

@XStreamAlias("attribute")
public class XmlTargetAttribute {

   /** name attribute of attribute node */
   @XStreamAsAttribute
   public String name;
}

在xmlAttribute.attributes中执行toXml()方法后,我有两个XmlTargetExcludedAttribute实例而不是XmlTargetAttribute。

准确地说:XmlTargetExcludedAttribute和XmlTargetAttribute类只是为了便于阅读,实际上它们是不同的。

如何解释要使用的课程?

1 个答案:

答案 0 :(得分:1)

您可以在每个列表值属性上注册本地NamedCollectionConverter,而不是全局别名这两个不同的类:

public class XmlGlobal {
   @XStreamConverter(value=NamedCollectionConverter.class, useImplicitType=false,
      strings={"attribute"}, types={XmlTargetExcludedAttribute.class})
   public List<XmlTargetExcludedAttribute> excluded;
}

public class XmlTargetExcludedAttribute {
   /** name attribute of class node */
   @XStreamAsAttribute
   public String name;
}


public class XmlAttribute {

   /** list of target attributes */
   @XStreamConverter(value=NamedCollectionConverter.class, useImplicitType=false,
      strings={"attribute"}, types={XmlTargetAttribute.class})
   public List<XmlTargetAttribute> attributes;
}

public class XmlTargetAttribute {

   /** name attribute of attribute node */
   @XStreamAsAttribute
   public String name;
}