我有一个类似下面的 java 字符串,它有多行和空格。需要将它们全部删除,使它们成为一行。
这些是 xml 标签,编辑器不允许包含小于符号
<paymentAction>
Authorization
</paymentAction>
应该成为
<paymentAction>AUTHORIZATION</paymentAction>
提前致谢
Calling theString.replaceAll("\\s+","")
will replace all whitespace sequences with the empty string. Just be sure that the text between the tags doesn't contain spaces too, othewerise they'll get removed too.
您本质上想要将您拥有的 XML 转换为Canonical Form。以下是一种方法,但它需要您使用该库。如果您不想依赖外部库,那么您的另一个选择是使用 XSLT。
Apache XML Security 项目中的Canonicalizer类:
注意:通常不建议处理非 xml 感知 API (String.replaceAll()),因为您最终会处理特殊/异常情况。
这是一个开始。可能还不够,但应该朝着正确的方向发展。
xml.replaceAll(">\\s*", ">").replaceAll("\\s*<, "<");
但是,我想说必须有一种方法可以从 XML 创建文档,然后按照 Pangea 的建议以规范的形式对其进行序列化。