我有 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>
最佳答案
我认为您问题的答案是,使用任何现成的 XML 序列化程序都无法完成此操作。
我同意这个要求,因为我也有这样格式的 XML 文件。但我认为这是一个非常罕见的用例,如果您想解决它,您需要编写自己的序列化器。
关于Java - 保存 XML 后保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807426/