3

我正在使用 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?

4

1 回答 1

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;
}
于 2013-05-13T03:41:10.103 回答