【问题标题】:Xstream parsing multiple listXstream解析多个列表
【发布时间】:2012-12-11 09:43:58
【问题描述】:

我有一个 xml 文件,其中根元素中有多个数组。每当我尝试使用隐式集合声明时,xstream 只处理最后一个声明,其他一切都保持为空。在下面的代码中,第一个数组 ERRORS 保持为空,而 DEBITS 被解析。

public class XMLParser {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args){
        String xmlString = "<DebitsWSDS xmlns=\"\"> " + 
                                 "  <DEBITS> " + 
                                 "    <DEBIT_ID>-1</DEBIT_ID> " + 
                                 "  </DEBITS> " + 
                                 "  <DEBITS> " + 
                                 "    <DEBIT_ID>-2</DEBIT_ID> " + 
                                 "  </DEBITS> " + 
                                 "  <ERRORS> " + 
                                 "    <ERROR_ID>1</ERROR_ID> " + 
                                 "  </ERRORS> " + 
                                 "  <ERRORS> " + 
                                 "    <ERROR_ID>2</ERROR_ID> " + 
                                 "  </ERRORS> " + 
                            "</DebitsWSDS> ";
        DebitsWSDS debitsWSDS;
        try {
            debitsWSDS = convertFeesSetXMLResultToDebitsWSDS(xmlString);
            System.out.println(debitsWSDS.ERRORS==null);
            System.out.println(debitsWSDS.DEBITS==null);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


private static DebitsWSDS convertFeesSetXMLResultToDebitsWSDS(String xml) throws Exception{

        XStream xstream = new XStream(new StaxDriver());
            xstream.alias("DebitsWSDS", DebitsWSDS.class);
        xstream.addImplicitCollection(DebitsWSDS.class, "DEBITS");
        xstream.addImplicitCollection(DebitsWSDS.class, "ERRORS");
        xstream.alias("ERROR_ID", String.class);
        //System.out.println(xml);
        DebitsWSDS debitsWSDS =(DebitsWSDS)xstream.fromXML(xml);
        return debitsWSDS;
    }

}




public class DebitsWSDS {

        public List<ERROR> ERRORS;
        public List<DEBIT> DEBITS;

    public class ERROR {
        public String ERROR_ID;
    }

    public class DEBIT {
        public String DEBIT_ID;
    }

}

【问题讨论】:

    标签: java xml-parsing xstream


    【解决方案1】:

    我不太确定你希望它做什么。 XStream 是一个 bean/XML 映射工具,您可以有效地将两个 XML 列表映射到 bean 中的同一 List 元素。如果你真的想要那个 XML 结构,我会使用 SAX 解析器或类似的工具来构造你的 bean,创建一个空列表并让解析器回调添加到该列表中。

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 2017-05-06
      • 2021-08-21
      • 2016-03-16
      • 2015-05-16
      • 1970-01-01
      相关资源
      最近更新 更多