简体   繁体   中英

Conditionally delete Parent Node if Children nodes are empty

As the title describes I am trying to take xml like this:

<Measurement>
    <Name>Board_1_Output_0</Name>
    <LongIdentifier>Board 1 Output 0<LongIdentifier/>
    ...
    <ECUAddress>2000000F</ECUAddress>
</Measurement>
<Measurement>
    <Name/>
    <LongIdentifier/>
    ...
    <ECUAddress/>
</Measurement>

and conditionally delete <Measurement> if any child nodes of <Measurement> are empty like this:

<Measurement>
    <Name>Board_1_Output_0</Name>
    <LongIdentifier>Board 1 Output 0<LongIdentifier/>
    ...
    <ECUAddress>2000000F</ECUAddress>
</Measurement>

My current xslt, for this section, looks like this:

<xsl:for-each select="Measurement">
    <xsl:text>/begin MEASUREMENT</xsl:text>
    <xsl:text>/* Name           */&#x09;</xsl:text>
    <xsl:value-of select ="Name"/>
    <xsl:apply-templates select="LongIdentifier">
    <xsl:text>ECU_ADDRESS&#x09;&#x09;&#x09;&#x09;</xsl:text>
    <xsl:value-of select ="ECUAddress"/>
<xsl:text>/end MEASUREMENT</xsl:text>
</xsl:for-each ><!-- Measurement -->

I thought I could conditionally look at each section and not print any <Measurment> XML tags if ANY of the children tags are empty, however, I can only achieve leaving the parent <Measurement> element as such:

<Measurement></Measurement>

Is there a way to delete the parent xml node when I find that I have an empty child in the same xslt stylesheet? Or do I need to run the xml through a different stylesheet to delete any XML nodes that have empty children?

You could use some XPath in your for-each to filter out <Measurement> elements. If you want to remove all such elements where any child element is empty, you could do something like:

<xsl:for-each select="Measurement[not(*[. = ''])]">
     ....
</xsl:for-each>

ie only select <Measurement> elements where there are not any child elements that are empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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