如何通过XStream读取具有属性的列表元素

时间:2013-05-09 11:33:57

标签: java xml xml-parsing xstream

我正在使用XStream来阅读下面的示例xml文件。

<list>
    <file>/setup/x86-linux2/bin/zip.txt</file>
    <file type="dir">/src/bin/</file>
    <name>test xml</name>
</list>

以下是我在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”。

我的问题是如何通过XStream读取xml示例?

1 个答案:

答案 0 :(得分:4)

迁移到 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;
}