Java - 保存 XML 后保留空格

标签 java xml dom whitespace

我有 XML 文件,我只需删除 1 个属性。

保存编辑后的 ​​XML 后,空格被删除,这是我需要的! (见图)

什么时候我会丢失空格?

当我解析文档中的 xml 时? 或者当我转换回 xml 时?

我已经使用了 Java Transformer 中的许多输出属性,例如:

    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
    transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "RequestMessage Code");

以避免其他格式问题。

有办法保留空白吗?

谢谢

编辑 1:我使用 XSL 来避免按字母顺序排列

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt" version="2.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" xalan:indent-amount="2"/>

    <!--Identity transformation (see http://www.w3.org/TR/xslt#copying).-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@Item"/>
            <xsl:apply-templates select="@Name"/>            
            <xsl:apply-templates select="@Include"/>
            <xsl:apply-templates select="@Variant"/>
            <xsl:apply-templates select="@Authorization"/>
            <xsl:apply-templates select="@Alias"/>
            <xsl:apply-templates select="@Source"/>
            <xsl:apply-templates select="@Field"/>
            <xsl:apply-templates select="@DgMemberName"/>
            <xsl:apply-templates select="@DgGroupName"/>
            <xsl:apply-templates select="@Target"/>
            <xsl:apply-templates select="@Host"/>
            <xsl:apply-templates select="@DataGroup"/>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Here u see the Diff between the two XML files

最佳答案

我认为您问题的答案是,使用任何现成的 XML 序列化程序都无法完成此操作。

我同意这个要求,因为我也有这样格式的 XML 文件。但我认为这是一个非常罕见的用例,如果您想解决它,您需要编写自己的序列化器。

关于Java - 保存 XML 后保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807426/

相关文章:

java - SpringBoot 和 GitLab CI 运行测试

java - 非常基本的 Java : For-Loop in Java method won't run

具有卡片样式和与 Google Play 音乐相同选项的 Android 列表项

c# - 使用 openxml 删除 x 命名空间

javascript - 复选框值始终为 'on'

javascript - 如何从数组添加到 <SVG> 元素

java - 用于多个包的 MOXy XmlNameTransformer

java - 如何检查字符串是否为int

c# - 基于文本树创建 XML

javascript - 比较两个页面的内容