格式化 XML 的十进制值 [英] Formatting decimal values for XML

查看:38
本文介绍了格式化 XML 的十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前遇到一个问题,我们正在连接的系统期望接收 XML,其中包含三个格式化为一位小数的双字段.我个人认为我们的系统应该能够以默认格式发送值,然后由其他系统根据自己的喜好格式化自己的表示,但可惜这似乎不是一个选项.

I have a problem currently where a system we are connecting to expects to receive XML which contains, among other things, three double fields formatted to one decimal place. Personally I feel that our system should just be able to send values in default format and then it's up to other systems to format their own representation as they please, but alas this doesn't seem to be an option.

我的基于 Java 的系统目前正在通过使用 XStream 将对象转换为 XML.我们有一个伴随 XML 的 XSD,并将各种元素定义为字符串、双精度、日期时间等.

My Java-based system is currently converting objects to XML through the use of XStream. We have an XSD which accompanies the XML and defines the various elements as string, double, dateTime, etc.

我有三个 double 字段,其中包含 12.5、100.123、5.23445 等值.现在它们几乎按原样转换为 XML.我需要的是将这些值在 XML 中格式化为一位小数;12.5、100.1、5.2 等

I have three double fields which hold values like 12.5, 100.123, 5.23445 etc. Right now they are converted pretty much as-is into the XML. What I need is these values to be formatted in the XML to one decimal place; 12.5, 100.1, 5.2, etc.

我已经简要地想到了实现此目的的选项:

I have briefly thought up options to accomplish this:

  • 不知何故,在将这些值传送到 XML 之前,让 Java 将这些值格式化为这种精度.也许 NumberFormat 可以做到这一点,虽然我认为这主要用于 String 输出.
  • 希望 XSD 能为我做这件事;我知道您可以在 XSD 中设置精度限制,但我不确定它是否实际处理舍入本身,还是只会说123.123 的值对于此架构无效"?
  • 使用 XSLT 以某种方式为我完成这项工作.

关于在这种情况下使用什么是可接受的"方式/最佳实践,我会选择你们的集体智慧.

I'd to pick your collective brains as to what would be the 'accepted' way / best practice to use in a situation like this.

谢谢,戴夫.

推荐答案

XStream has converters(教程).您必须注册自己的 Double 转换器来处理此问题.在转换器中使用 DecimalFormat 限制小数位数.

XStream has converters (tutorial). You would have to register your own Double converter that will handle this. In the converter use DecimalFormat to limit the number of decimal places.

这篇关于格式化 XML 的十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆