Xstream没有附加该字段的别名

时间:2014-07-02 15:07:30

标签: java xml xstream

我已经定义了我的xstream:

public static final String listToXMLTree(List<?> list, 
         Class<?> domainClass, Converter evtConverter ) {
    String xml = "";
    StringBuffer buff = new StringBuffer(1000);
    buff.append("<?xml version='1.0' encoding='iso-8859-1'?>");

    XStream xstream = new XStream(new DomDriver());
    if (list != null && list.size() > 0) {

        xstream.registerConverter(evtConverter);

        xstream.alias("rows", List.class);
        xstream.alias("row", Event.class );
        xstream.aliasField("child", Event.class, "hasChildren");

        xml = xstream.toXML(list);
    } else {
        buff.append("<rows/>");
    }
    xml = buff.append(xml).toString();
    System.out.println(xml);

    return xml;
}

但弹出的xml没有#34; hasChildren&#34;的任何别名。变量 - 为什么这样? xml看起来像这样:

<?xml version='1.0' encoding='iso-8859-1'?>
<rows>
  <row id="Puerto Rico692014-04-30 00:00:00.02014-07-29 00:00:00.0" xmlkids="1">
    <cell></cell>
    <cell>Puerto Rico</cell>
    <cell>103415</cell>
  </row>
</rows>

修改

这是我所拥有的事件类 - (在单独的注释中,我尝试使用XStream别名并删除上面的代码,手动创建它们但它也没有工作):

public class Event 
{
// Event parameters
private String region;
private boolean hasChildren;

public boolean isHasChildren() {
    return hasChildren;
}
public void setHasChildren(boolean hasChildren) {
    this.hasChildren = hasChildren;
}
public String getRegion() {
    return region;
}
public void setRegion(String region) {
    this.region = region;
}

}

evtConverter是一个转换器,它将Xstream吐出的xml映射到DHTMLx网格。

由于

1 个答案:

答案 0 :(得分:0)

这个答案归功于 Vertex - 为了正常工作,需要在别名之后添加转换器 - 我实际上重构了我的答案并让对象使用 { {3}} 而不是在方法中定义它们。这是代码:

/**
 * Method to convert list objects to XML using XStream API.
 * <p>
 * 
 * @param list
 * @param domainClass
 * @param columnIds
 */
public static final String listToXML(List<?> list, Class<?> domainClass,
        Converter converter) {
    String xml = "";
    StringBuffer buff = new StringBuffer(1000);
    buff.append("<?xml version='1.0' encoding='UTF-8'?>");

    XStream xstream = new XStream(new DomDriver());
    if (list != null && list.size() > 0) {

        xstream.alias("rows", List.class);

        xstream.processAnnotations(domainClass);
        xstream.registerConverter(converter);

        xml = xstream.toXML(list);
    } else {
        buff.append("<rows/>");
    }
    xml = buff.append(xml).toString();  
    return xml;

}