Home > OS >  Remove specific empty tag if empty
Remove specific empty tag if empty

Time:01-02

I need to remove all emtpy tags for one specific tag in the xml. I need to do this for only specific tag (Language) not all emtpy tags below are the sample xml and the xslt that I tried and the expected output

    <Data xmlns="http://schemas.ctac.local/inRiver/2019/01/test">
        <Item uniqueFieldTypeId="item">
            <Fields>
                <Field>
                    <Key>ItemNu</Key>
                    <Type>String</Type>
                    <Language/>
                    <Value>8718848195568</Value>
                </Field>
                <Field>
                    <Key>ItemNu</Key>
                    <Type>CVL</Type>
                    <Language/>
                    <Value>ST</Value>
                </Field>
                <Field>
                    <Key>ItemNu</Key>
                    <Type>CVL</Type>
                    <Language/>
                    <Value/>
                </Field>
            </Fields>
        </Item>
    </Data>

I am trying the below xslt but not giving the needed output

    <xsl:stylesheet version="1.0"
                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output omit-xml-declaration="yes"
                    indent="yes"/>
        <xsl:strip-space elements="*"/>
        <xsl:template match="node()|@*">
            <xsl:copy>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="Language/*[not(node())]"/>
    </xsl:stylesheet>

Output required is

  <Data xmlns="http://schemas.ctac.local/inRiver/2019/01/test">
    <Item uniqueFieldTypeId="item">
        <Fields>
            <Field>
                <Key>ItemNu</Key>
                <Type>String</Type>
                <Value>8718848195568</Value>
            </Field>
            <Field>
                <Key>ItemNu</Key>
                <Type>CB</Type>
                <Value>ST</Value>
            </Field>
            <Field>
                <Key>ItemNu</Key>
                <Type>CL</Type>
                <Value/>
            </Field>
        </Fields>
    </Item>
  </Data>

CodePudding user response:

Because your XML maintains a default namespace, simply assign a prefix to re-style <Language> node and use the dot predicate for string value check:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:doc="http://schemas.ctac.local/inRiver/2019/01/test">
    <xsl:output omit-xml-declaration="yes"
                indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="doc:Language[.='']"/>
</xsl:stylesheet>
  • Related