2012-02-29 66 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中有多少個對象。它似乎沒有告訴我的對象數量或大小的方法...