Search code examples
javaxmlxstream

How to remove space from xml tag using XStream?


I have the xml below that has a number value

<detalhe>
  <numLinha>1048  </numLinha>
</detalhe

the tag numLinha will be converted to a number attibute in java, however i receive the folow message because there are spaces at the end of tag:

Exception in thread "main"  
com.thoughtworks.xstream.converters.ConversionException: For input string "1048                    "

@XStreamAlias("detalhe")
public class BodyDetail implements Serializable {

   private static final long serialVersionUID = -1000785985130865301L;

   @XStreamAlias("numLinha")
   private Integer lineNumber;
}

Solution

  • I solve my problem with a custom converter of Integer Type.

    1. First i created the converter:

      package converter;
      
      import com.thoughtworks.xstream.converters.Converter;
      import com.thoughtworks.xstream.converters.MarshallingContext;
      import com.thoughtworks.xstream.converters.UnmarshallingContext;
      import com.thoughtworks.xstream.io.HierarchicalStreamReader;
      import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
      
      public class IntegerConverter implements Converter {
      
         @SuppressWarnings("rawtypes")
         @Override
         public boolean canConvert(Class clazz) {
             return clazz.equals(Integer.class);
         }
      
         @Override
         public void marshal(Object object, HierarchicalStreamWriter writer,
              MarshallingContext context) {
         }
      
         @Override
         public Object unmarshal(HierarchicalStreamReader reader,
              UnmarshallingContext context) {
            String text = (String)reader.getValue();
            Integer number = Integer.parseInt(text.trim());
            return number;
         }    
      }
      
    2. I registered the converter:

       public class XMLRead {
      
         public static void main(String[] args) {
      
            XStream xStream = new XStream();    
            xStream.registerConverter(new IntegerConverter());
         }
       }