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 读取具有属性的列表元素
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
