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

后端 未结 1 1314
温柔的废话
温柔的废话 2021-01-26 17:06

I would like to serialize an object to an XML of this form with XStream.

text

There already is a solutio

1条回答
  •  有刺的猬
    2021-01-26 17:40

    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:

        text
        attr: value
        content: text
    

    0 讨论(0)
提交回复
热议问题