0

首先让我说这是我第一次尝试使用 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());
    }

}

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

4

2 回答 2

1

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

于 2013-07-18T13:28:37.707 回答
0

@伊恩

没关系!我做了你让我做的事。结果看起来有点像这样:

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

那是完美的。谢谢!

于 2013-07-18T13:57:20.307 回答