2011-10-30 25 views
1

我有XML的一個字符串,它看起來像這樣:使用使用XStream轉換器時,一個元素有一個值和子元素

<e1 atr1="3" atr2="asdf"> 
<e1b atr3="3" atr4="asdf"> 
    <e1c atr5="3" atr6="asdf"/> 
    TestValue1 
</e1b> 
<e1b atr3="3" atr4="asdf"> 
    <e1c atr5="3" atr6="asdf"/> 
    TestValue2 
</e1b> 
</e1> 

它比其他XML我在過去的分析不同,因爲E1B元素具有值TestValue1TestValue2以及子元素(e1c)。

如果一個元素同時具有屬性和值,則必須爲xstream創建一個自定義轉換器來解析它。我的嘗試在下面,但因爲e1b元素有屬性,子元素和值,我不知道如何處理它。在我的轉換器中,我遺漏了所有對子元素e1c的引用。我需要將什麼添加到轉換器才能正確處理e1c元素?現在,當我做xstream.fromXML()時,e1c值沒有被填充。

public class e1Converter implements Converter { 

@SuppressWarnings("rawtypes") 
public boolean canConvert(Class clazz) { 
    return e1b.class == clazz; 
} 

public void marshal(Object object, HierarchicalStreamWriter hsw, 
     MarshallingContext mc) { 
    e1b e = (e1b) object; 
    hsw.addAttribute("atr3", e.getAtr3()); 
    hsw.addAttribute("atr4", e.getAtr4()); 

    hsw.setValue(e.getE1bValue()); 
} 

public Object unmarshal(HierarchicalStreamReader hsr, 
     UnmarshallingContext uc) { 

    e1b e = new e1b(); 
    e.setAtr3(hsr.getAttribute("atr3")); 
    e.setAtr4(hsr.getAttribute("atr4")); 
    e.setE1bValue(hsr.getValue()); 

    return e; 
} 

} 

回答

1

據約克的XStream的郵件列表:

其實你不能。 XStream無法讀取混合模式XML,即其中 文本和子元素在相同級別混合的XML。讀者將 只是在未定義的行爲。這種XML並不適用於XStream的分層流模型。什麼是父母的價值 這裏:

<parent> what <child/>is <child/> the <child/>value <child/>now? </parent 

對不起,約爾格

+0

這是上面提到的http://article.gmane.org/gmane.comp.java郵件列表線程的鏈接。 xstream.user/7898 – user963263

相關問題