2013-07-18 47 views
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添加到我的构建路径中。我试着遵循以下几个教程,但似乎无法弄清楚,为什么我收到此错误:xstream解析器错误:java.lang.ArrayIndexOutOfBoundsException:-1

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()); 
    } 

} 

我希望能提供任何见解。非常感谢你!

回答

1

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

+0

我不确定你在这里是什么意思。我发现这些方法存在,但我不知道如何传递文件,Url或Inputstream。我将如何创建一个文件对象? – unsingefou

0

@Ian

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

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

这是完美的。谢谢!

+0

虽然对于您在问题中提供的特定文件,这将是正确的,但要注意,如果XML文件的字符编码与平台上的默认编码相同,则“FileReader”只能在一般情况下使用。使用带'File'或'InputStream'的'fromXML'通常好得多,而不是'Reader',所以XML解析器可以检测和使用文件的正确编码--xstream。 fromXML(new File(“C:\\ Users \\ name \\ Desktop \\ visualMonitor \\ vBlock.xml”))' –

相关问题