2011-07-25 87 views
0

我想我可能會用XStream工作「放大」太多,但我試圖編排一個XML流,其中包含各種大型複雜對象,並且每個對象往往有很多的標籤,如:使用XStream閱讀標籤的內容

<name type="string">My Name</name> 
<speed type="dice">2d6</speed> 

所以我創建了一個「TypedString」對象,以包串的概念,一個類型的屬性,像這樣:

import com.thoughtworks.xstream.annotations.XStreamAsAttribute; 
public class TypedString { 
    @XStreamAsAttribute 
    private String type; 
    private String value; 

    public TypedString(String type, String value) { 
     this.type = type; 
     this.value = value; 
    } 
    // getters omitted 
} 

現在,我知道這一定是錯過了一些東西 - 我怎樣才能得到使用標籤內容設置的「值」變量(例如對於冷杉例如上面所示,類型將是「字符串」和值將是「我的名字」)。

我寫了這個簡短的單元測試:

public class TypedStringTest { 
    private XStream xStream; 

    @Before 
    public void setUp() { 
     xStream = new XStream(); 
     xStream.processAnnotations(TypedString.class); 
     xStream.alias("name", TypedString.class); 
    } 

    @Test 
    public void testBasicUnmarshalling() { 
     TypedString typedString = (TypedString) xStream.fromXML("<name type=\"string\">Name</name>"); 
     assertEquals("string", typedString.getType()); 
     assertEquals("Name", typedString.getValue()); 
    } 
} 

第二斷言哪個失敗。

是否有需要添加到TypedString類來使它工作的註釋?或者我在這裏真的放大了太多(例如,是否應該在包含這些標籤的類的註釋中完成這些操作?)。 @XStreamAsAttribute註解看起來不像它可以從父標記中使用 - 它需要在代表應用於的標記的對象上定義,從我可以說的。因此,我創造了另外一種美化的字符串,我覺得XStream應該在沒有我的暗示幫助下編組。

簡而言之,我失去了什麼?

+0

環顧網站尋找答案,我看到的最好的轉換器 - 是否真的沒有辦法做到這一點與XStream中的註釋? – Phantomwhale

回答

0
@XStreamAlias("name") 
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"value"}) 
public class TypedString { 
    private String type; 
    private String value; 
} 
0
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"value"}) 
public class TypedString { 
    @XStreamAsAttribute 
    private String type; 
    private String value; 
} 

它爲單行值。

如果你有這樣的東西,值將是一些空白。

<name type="string"> 
    My Name 
</name> 

在這種情況下,值將是「」。

+0

我想知道如何獲取該多行案例中的值。 – Rodolfo