从xml文件中检索存储为字符串的非根元素数组

时间:2013-04-10 04:28:26

标签: java parsing xstream

我有一个场景,其中我有以下xml和类

XML:

<packages>
<package>
<name>class1</name>
      <classes>300</classes>
      <functions>21</functions>
      <ncss>283</ncss>
      <javadocs>20</javadocs>
      <javadoc_lines>111</javadoc_lines>
      <single_comment_lines>11</single_comment_lines>
      <multi_comment_lines>221</multi_comment_lines>
</package>
</packages>

Java类:

Class Package {

//all variables and setters getters
}

class Packages {
public  ArrayList<Package> x;
//add and remove methods for x
}

在mainClass中我有:

    BufferedReader br = new BufferedReader(new FileReader(new                                                    
File("C:\\old_code_complexity.xml")));
    String line;
    StringBuilder sb = new StringBuilder();

    while((line=br.readLine())!= null){
        sb.append(line.trim());
    }

    String x = sb.toString();

    XStream xstream = new XStream();
    xstream.alias("package", Package.class);
    xstream.alias("packages", Packages.class);
    xstream.addImplicitCollection(Packages.class, "x");



    Packages pList = (Packages)xstream.fromXML(x);
    Package pack = (Package) xstream.fromXML(x);

    System.out.println(xstream.toXML(pack));

println之前的行每次都会出错

Exception in thread "main" java.lang.ClassCastException: dummyCompare.input.Packages     cannot be cast to dummyCompare.input.Package
    at dummyCompare.Logic.mainClass.main(mainClass.java:41)

如何管理此强制转换操作,以便检索我可以在代码中操作的对象数组?

1 个答案:

答案 0 :(得分:0)

为什么要尝试将Packages对象转换为Package对象?只需为Packages创建 getter

public  ArrayList<Package> getPackageList() {
  return x;
}

而不是施展它:

Packages pList = (Packages)xstream.fromXML(x);
ArrayList<Package> pack = pList.getPackageList();