如何使用XStream从xml标记中删除空格?

时间:2016-08-17 20:22:09

标签: java xml xstream

我的xml下面有一个数字值

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

标签numLinha将在java中转换为attibute,但是我收到了folow消息,因为标签末尾有空格:

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;
}

1 个答案:

答案 0 :(得分:0)

我使用Integer Type的自定义转换器解决了我的问题。

  1. 首先我创建了转换器:

    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. 我注册了转换器:

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