1

How to use more than one @XStreamAlias annotation on same element. When I do like this:

@XStreamAlias("alias1")
@XStreamAlias("alias2")
class ABC{
//
}

I get compilation error. Is there any way to achieve this?

Vivek Mangal
  • 532
  • 1
  • 8
  • 24
  • My opinion that is not possible with annotation, but you can do it with alias registration by XStream initialisation: `xStream.alias("alias1", ABC.class);` – Mark Mar 15 '17 at 22:34
  • But if I have to parse xml many times then I have to use this many times with each instance of XStream. Any other way? – Vivek Mangal Mar 20 '17 at 10:15
  • What do you mean with "parse xml many times"? – Mark Mar 20 '17 at 11:52
  • I mean I have to parse xml in different files. I can't parse it only once because my xml changes with time. – Vivek Mangal Mar 21 '17 at 06:56
  • Good, then you can use the solution without annotation, see my answer example. – Mark Mar 22 '17 at 10:33
  • Hi, if the answer satisfy you requirements - then please mark it as solution. – Mark Mar 24 '17 at 18:23

2 Answers2

-1

Here is example with programmatic way:

import java.io.InputStream;
import java.util.List;

import org.junit.Test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import lombok.Data;


public class MultiAlias {

    @Test
    public void smokeTest() {
        InputStream file = MultiAlias.class.getResourceAsStream("MultiAliasTest.xml");
        XStream xStream = new XStream();
        xStream.ignoreUnknownElements();
        xStream.processAnnotations(Parent.class);
        xStream.alias("child", Child.class);
        xStream.alias("kind", Child.class);

        Parent parent = (Parent) xStream.fromXML(file);

        System.out.println(parent);
    }

    @XStreamAlias("parent")
    @Data
    public class Parent {

        @XStreamAsAttribute
        private String name;

        private List<Child> children;

    }

    @Data
    public class Child {
        private String name;
    }

}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<parent name="Adam">
        <age>33</age>
        <children>  
            <child>
                <name>Iva</name>
            </child>
            <kind>
                <name>Peter</name>
            </kind>
        </children>
</parent>

Output:

MultiAlias.Parent(name=Adam, children=[MultiAlias.Child(name=Iva), MultiAlias.Child(name=Peter)])
Mark
  • 17,887
  • 13
  • 66
  • 93
-1

I think, as Mark says, that is not possible with annotations (can't find anything in the web). In my particular case, as a walk arround, what I did was to extend from the base class (ABC in the Vivek example) and put their own annotation in the child classes and use those classes. Bud the solution depends on your code implementation. Regards.-

ABC class

@XStreamAlias("alias1") DFG extends ABC

@XStreamAlias("alias2") XYZ extends ABC

demian
  • 632
  • 7
  • 14