How to read list elements with attribute via XStream(如何通过 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 读取具有属性的列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过 XStream 读取具有属性的列表元素
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01