问题
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>
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);
}
}
}
The output of my program is,
test xml
null
null
Looks like XStream does not support using annotation '@XStreamImplicit' and '@XStreamConverter' at the same time.
My question is how should I do to read the example xml via XStream?
回答1:
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;
}
来源:https://stackoverflow.com/questions/16460810/how-to-read-list-elements-with-attribute-via-xstream