简体   繁体   中英

Simple Framework XML remove empty attribute

Simple question! I have such a class, and if the attribute is empty (or just null) then this attribute should not appear at all in the generated XML file

XML File: (note empty string in attribute abc, i don't want something like that!)

  <root abc="">
     <example>somethin</example>
     </root>

Java Class

 @Root
 public class Data {

 @Element(name="example">
 private String value;

 @Attribute(name="abc", required=false)
 private String s;

 public String getString() {
     return s;           
 }

I tried with a @Convert but it works only with @Element... Is there any way to remove the attribute in the xml file when it is empty?

Use a custom XMLAdapter as such:

public class ExampleAdapter extends XmlAdapter<String, String> {

@Override
public String marshal(String exampleString) throws Exception {
    return exampleString;
}

@Override
public String unmarshal(String exampleString) throws Exception {
    if (exampleString.isEmpty()) {
        return null;
    }

    return exampleString;
}}

And then just associate your property with it:

@XmlAttribute
@XmlJavaTypeAdapter(ExampleAdapter.class)
public void setExample(String example) {
    this.example = example;
}

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