本文介紹了如何通過 XStream 讀取具有屬性的列表元素的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用 XStream 讀取下面的示例 xml 文件.
I'm using XStream to read below example xml file.
<list>
<file>/setup/x86-linux2/bin/zip.txt</file>
<file type="dir">/src/bin/</file>
<name>test xml</name>
</list>
下面是我閱讀上面xml的代碼,
Below is my code for reading above xml,
public class ListWithConverter {
public static class FileConvertor implements Converter {
public boolean canConvert(final Class clazz) {
return clazz.equals(MyFile.class);
}
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
throw new UnsupportedOperationException("Not supported to write file element yet."); //$NON-NLS-1$
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
MyFile file = new MyFile();
for (Iterator<String> iter = reader.getAttributeNames(); iter.hasNext(); ){
String name = iter.next();
if (name.equals("type")) //$NON-NLS-1$
file.type = reader.getAttribute(name);
}
file.path = reader.getValue();
return file;
}
}
@XStreamAlias("list")
public class MyList {
@XStreamAlias("name")
String name;
@XStreamImplicit(itemFieldName="file") @XStreamConverter(FileConvertor.class)
List<MyFile> files;
}
public static class MyFile {
String type;
String path;
}
public static void main(String[] args) throws MalformedURLException, IOException {
XStream xstream = new XStream();
xstream.setClassLoader(MyList.class.getClassLoader());
xstream.processAnnotations(MyList.class);
InputStream stream = new File("test.xml").toURL().openStream();
MyList list = (MyList)xstream.fromXML(stream);
System.out.println(list.name);
for (MyFile f : list.files) {
System.out.println(f.path);
}
}
}
我的程序的輸出是,
test xml
null
null
看起來 XStream 不支持同時使用注解@XStreamImplicit"和@XStreamConverter".
Looks like XStream does not support using annotation '@XStreamImplicit' and '@XStreamConverter' at the same time.
我的問題是如何通過 XStream 讀取示例 xml?
My question is how should I do to read the example xml via XStream?
推薦答案
我在遷移到XStream 1.4.x后找到了解決方案,
I found a solution after migrating to XStream 1.4.x,
@XStreamAlias("list")
public class MyList {
@XStreamAlias("name")
String name;
@XStreamImplicit(itemFieldName="file")
List<MyFile> files;
}
@XStreamAlias("file")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"path"})
public static class MyFile {
@XStreamAlias("type")
@XStreamAsAttribute
String type;
String path;
}
這篇關于如何通過 XStream 讀取具有屬性的列表元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!