如何通过阅读与XStream的属性列表元素(How to read list elements wi

2019-09-02 08:34发布

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

Answer 1:

我发现了一个解决方案迁移到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;
}


文章来源: How to read list elements with attribute via XStream