如何使用 XStream 从 xml 标签中删除 space?
How to remove space from xml tag using XStream?
我下面的xml有一个数值
<detalhe>
<numLinha>1048 </numLinha>
</detalhe
标签 numLinha 将在 java 中转换为数字属性,但是我收到以下消息,因为标签末尾有空格:
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;
}
我用整数类型的自定义转换器解决了我的问题。
首先我创建了转换器:
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;
}
}
我注册了转换器:
public class XMLRead {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.registerConverter(new IntegerConverter());
}
}
我下面的xml有一个数值
<detalhe>
<numLinha>1048 </numLinha>
</detalhe
标签 numLinha 将在 java 中转换为数字属性,但是我收到以下消息,因为标签末尾有空格:
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;
}
我用整数类型的自定义转换器解决了我的问题。
首先我创建了转换器:
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; } }
我注册了转换器:
public class XMLRead { public static void main(String[] args) { XStream xStream = new XStream(); xStream.registerConverter(new IntegerConverter()); } }