2012-02-29 47 views
1

我想将XML文件用作我正在处理的NLP项目的字典。我目前有一个“Words”类,它是“Word”对象的向量。使用XStream将XML文件读入对象矢量

public class Words { 

private Vector<Word> vect; 

public Words(){ 
    vect = new Vector<Word>(); 
} 

public void add(Word w){ 
    vect.add(w); 
} 

的 “字” 类看起来是这样的:

public class Word { 
private String name; 
private String partOfSpeech; 
private String category; 
private String definition; 
} 

我已成功通过使用此代码写的 “字” 矢量使用XStream的XML:

public class Writer { 

public static void main(String[] args) { 

    XStream xstream = new XStream(); 
    xstream.alias("words", Words.class); 
    xstream.alias("word", Word.class); 
    xstream.addImplicitCollection(Words.class, "vect"); 

    Words vect = new Words(); 
    vect.add(new Word("dog", "noun", "animal", "a domesticated canid, Canis familiaris, bred in many varieties")); 
    vect.add(new Word("cat", "noun", "animal", "a small domesticated carnivore, Felis domestica or F. catus, bred in a number of varieties")); 


    try { 
     FileOutputStream fs = new FileOutputStream("c:/dictionary.xml"); 
     xstream.toXML(vect, fs); 
    } catch (FileNotFoundException e1) { 
     e1.printStackTrace(); 
    } 
} 
} 

这一切似乎工作正常,并给我以下XML文件:

<words> 
    <word> 
     <name>dog</name> 
     <partOfSpeech>noun</partOfSpeech> 
     <category>animal</category> 
     <definition>a domesticated canid, Canis familiaris, bred in many varieties</definition> 
    </word> 
    <word> 
     <name>cat</name> 
     <partOfSpeech>noun</partOfSpeech> 
     <category>animail</category> 
     <definition>a small domesticated carnivore, Felis domestica or F. catus, bred in a number of varieties</definition> 
    </word> 
</words> 

我的问题是如何使用XStream将此XML文件读回到对象的矢量中?

回答

1

我能够读取该文件中使用下面的代码:

public class Reader { 
public static void main(String[] args) { 

    XStream xstream = new XStream(new DomDriver()); 
    try { 
    FileInputStream fis = new FileInputStream("c:/dictionary.xml"); 
    ObjectInputStream in = xstream.createObjectInputStream(fis); 
    xstream.alias("word", Word.class); 

    Word a = (Word)in.readObject(); 
    Word b = (Word)in.readObject(); 

    in.close(); 

    System.out.println(a.toString()); 
    System.out.println(b.toString()); 

    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
    } catch (ClassNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }  
} 

}

现在,而不是说:

Word a = (Word)in.readObject(); 
Word b = (Word)in.readObject(); 

我想阅读的对象通过使用循环将其转换为矢量。我现在唯一的问题是如何知道ObjectInputStream中有多少个对象。它似乎没有告诉我的对象数量或大小的方法...