简体   繁体   中英

Unwanted class attribute from using simple xml

I'm currently using the simple XML library, and the tutorial didn't have a runnable example for ElementLists. http://simple.sourceforge.net/home.php

I have an example class:

@Root
public class Example {

@ElementList
private List<String> text;

@Attribute
private int index;

public Example() {
   super();
}  

public Example(List<String> text, int index) {
   this.text = text;
   this.index = index;
}

public List<String> getMessage() {
  return text;
}

public int getId() {
  return index;
}
}

And a simple class for running:

public class M {

public static void main(String[] args) throws Exception {
    Serializer serializer = new Persister();
    List<String> l = new LinkedList<String>();

    l.add("f");
    l.add("f");

    Example example = new Example(l, 123);
    File result = new File("example.xml");

    serializer.write(example, result);
}

}

The XML that I generate is:

<example index="123">
<text class="java.util.LinkedList">
  <string>f</string>
  <string>f</string>
</text>
</example>

Why am I getting the class="java.util.LinkedList"? I'm confused on how remove this attribute.

You can use the VisitorStrategy to intercept the serialization of the object.

Strategy strategy = new VisitorStrategy(new Visitor() {

    @Override
    public void write(Type type, NodeMap<OutputNode> node) throws Exception {
        if ("text".equals(node.getName())){
            node.remove("class");
        }
    }
    ...
});

I was working on the same problem and I got a way to avoid the 'class' attribute.

Instead of using @ElementList like this:

@ElementList(name="Files", entry="File")

You can use @Path annotation with the @ElementList as follows:

@Path(value="Files")
@ElementList(inline=true, entry="File")

You can use an Implementation for an @ElementList List, example:
LinkedList instead of List.

@ElementList
private LinkedList<String> texts;

This will avoid class attribute not wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM