XStream : node with attributes and text node in xstream 1.3.1?

懵懂的女人 提交于 2019-12-02 07:34:19

It's possible with some hacks. The main idia is to use a modified ToAttributedValueConverter from 1.4.7.

  1. Copy ToAttributedValueConverter into your package
  2. Copy UseAttributeForEnumMapper into your package
  3. Replace ToAttributedValueConverter#fieldIsEqual as follows:

    private boolean fieldIsEqual(FastField field) {
        return valueField.getName().equals(field.getName())
                && valueField.getDeclaringClass().getName()
                        .equals(field.getDeclaringClass().getName());
    }
    
  4. Replace the Constructor in UseAttributeForEnumMapper as follows:

    public UseAttributeForEnumMapper(Mapper wrapped) {
        super(wrapped, null);
    }
    

It is not possible to use the @XStreamConverter annotation, becouse the ToAttributedValueConverter has a constrcutor that needs some extra information, like the value field. But you can use XStream#registerConverter alternativly. So your class have to look like:

    @XStreamAlias("node")
    public class Node {
        private String attr;
        private String content;

        public void setAttr(String attr) { this.attr = attr; }
        public String getAttr() { return attr; }
        public void setContent(String content) { this.content = content; }
        public String getContent() { return content; }
    }

And a example that shows how to configure xstream for this converter:

    public static void main(String[] args) {
        final Node node = new Node();
        node.setAttr("value");
        node.setContent("text");

        final XStream xstream = new XStream();
        configureXStream(xstream);

        final String xml = xstream.toXML(node);
        System.out.println(xml);

        final Node node2 = (Node) xstream.fromXML(xml);
        System.out.println("attr: " + node2.getAttr());
        System.out.println("content: " + node2.getContent());
    }

    private static void configureXStream(final XStream xstream) {
        xstream.autodetectAnnotations(true);
        final Mapper mapper = xstream.getMapper();
        final ReflectionProvider reflectionProvider = xstream
                .getReflectionProvider();
        final ConverterLookup lookup = xstream.getConverterLookup();
        final Converter converter = new ToAttributedValueConverter(Node.class,
                mapper, reflectionProvider, lookup, "content");
        xstream.registerConverter(converter);
    }

This program prints out:

    <node attr="value">text</node>
    attr: value
    content: text
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!