xstream解析器错误:java.lang.ArrayIndexOutOfBoundsException:-1

时间:2013-07-18 13:08:12

标签: java xstream

首先我要说这是我第一次尝试使用xStream。我试图解析一个xml文件并使用该数据来构建一个java对象。我已将xstream-1.4.4.jar,xpp3_min-1.1.4c.jar,xmlpull-1.1.3.1.jar和kxml2-2.3.0.jar添加到我的构建路径中。我试过按照几个教程,但似乎无法弄清楚为什么我收到这个错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at com.thoughtworks.xstream.core.util.FastStack.pop(FastStack.java:42)
    at com.thoughtworks.xstream.io.xml.AbstractPullReader.move(AbstractPullReader.java:125)
    at com.thoughtworks.xstream.io.xml.AbstractPullReader.moveDown(AbstractPullReader.java:103)
    at com.thoughtworks.xstream.io.xml.XppReader.<init>(XppReader.java:63)
    at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:54)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:913)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:904)
    at ParseTesting.Testing.main(Testing.java:10)

xml文件如下所示:

<?xml version="1.0" encoding="ISO-8859-1"?>

<vblock>
    <name>vBlock1</name>
    <status>online</status>
    <storage>2.2</storage>
    <cpu>2.5</cpu>
</vblock>

现在,这是我想要创建的对象的相应类:

package ParseTesting;

public class Vblock {
    private String name;
    private String status;
    private double storage;
    private double cpu;

    /*public Vblock(String n, String stat, double stor, double proc){
        name = n;
        status = stat;
        storage = stor;
        cpu = proc;
    }*/

    public String getName(){
        return this.name;
    }
    public String getStatus(){
        return this.status;
    }
    public double getStorage(){
        return this.storage;
    }
    public double getCpu(){
        return this.cpu;
    }

}

最后,实际解析我正在尝试:

package ParseTesting;

import com.thoughtworks.xstream.XStream;

public class Testing {
    public static XStream xstream = new XStream();

    public static void main(String[] args){
        xstream.alias("vblock", Vblock.class);  
        Vblock v1 = (Vblock)xstream.fromXML("vBlock.xml");

        System.out.println(v1.getName());
    }

}

我很感激可以提供的任何见解。非常感谢你!

2 个答案:

答案 0 :(得分:1)

采用fromXML参数的String方法需要一个包含要解组的实际XML的字符串,而不是包含文件名的字符串。如果您要从文件中解析,则需要使用fromXMLFileURL的其他InputStream方法之一。

答案 1 :(得分:0)

@Ian

没关系!我做了你告诉我要做的事。结果看起来像这样:

FileReader r = new FileReader("C:\\Users\\name\\Desktop\\visualMonitor\\vBlock.xml");
        xstream.alias("vblock", Vblock.class);
        Vblock v1 = (Vblock)xstream.fromXML(r);

这很完美。谢谢!