简体   繁体   English

使用XSLT删除所有带有和不带有现有属性的空XML元素

[英]Remove all empty XML elements with and without existing attributes with XSLT

I need to clean up a large XML file after localization. 本地化后,我需要清理一个大型XML文件。 The segments that did not need to be translated were replaced with a placeholder and then in the output were replaced with nothing. 不需要翻译的句段被替换为占位符,然后在输出中被替换为空。 However, the surrounding tags remained as regexing all potential tags surrounding those now-missing content appeared to be too complex and dirty too. 但是,周围的标签仍然保留着,因为重新包装围绕那些现在缺少的内容的所有潜在标签似乎也太复杂和肮脏了。

When a transformation scenario is applied, there are a lot of blank tables, lines, etc. that are remnant XML elements of the deleted content. 应用转换方案时,有很多空白表,行等,它们是已删除内容的剩余XML元素。 I need all those empty tags and their empty children too to go regardless whether they have attributes or not. 我也需要所有这些空标记及其空子代,无论它们是否具有属性。 I was able to find the following solution, however it does mention that it will only work for only elements without attributes without taking care of the elements with children (also empty). 我能够找到以下解决方案,但是它确实提到它仅适用于没有属性的元素,而不会处理带有子元素(也为空)的元素。 What adjustments are required for it to work for all empty elements even with attributes containing values? 即使具有包含值的属性,它也需要进行哪些调整才能适用于所有空元素? Any ideas would be appreciated. 任何想法,将不胜感激。

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*[descendant::text() or descendant-or-self::*/@*[string()]]">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@*[string()]">
    <xsl:copy/>
</xsl:template>

</xsl:stylesheet>

Whether it is necessary to cut off white-spaces from a string? 是否有必要从字符串中切除空格?

Here example with normalize-space: https://xsltfiddle.liberty-development.net/nbUY4kx/4 以下是具有规范化空间的示例: https : //xsltfiddle.liberty-development.net/nbUY4kx/4

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="@*|node()">
          <xsl:if test="normalize-space(.)!=''">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>    
          </xsl:if>
    </xsl:template>
</xsl:stylesheet>

and another example without: https://xsltfiddle.liberty-development.net/nbUY4kx/3 另一个没有以下示例: https : //xsltfiddle.liberty-development.net/nbUY4kx/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM