Remove node and previous node if matched node is empty

It is possible to remove parent node and previous parent node if the matched node is empty?

Example:

<div>
    <div>
        <p>Banana
        </p>
    </div>
    <table>
        <tbody>Not empty</tbody>
        <tr>
            <td>A</td>
        </tr>
    </table>
    <div>
        <p>Apple
        </p>
    </div>
    <table>
        <tbody></tbody>
    </table>
</div>

If <table>-><tbody> is empty I would like to remove <table> and previous <div> node.

Example output:

<div>
    <div>
        <p>Banana
        </p>
    </div>
    <table>
        <tbody>Not empty</tbody>
        <tr>
            <td>A</td>
        </tr>
    </table>
</div>

Upvotes: 0

Views: 47

Answers (1)

Michael Kay
Michael Kay

Reputation: 163458

There is no operation in XSLT to "remove" a node. A node is removed unless you actively copy it to the output. If the template rule that matches a node is empty (does nothing) then the node will effectively be removed. So you can write

<xsl:template match="div[following-sibling::*[1]
                        [self::table[not(string(tbody))]]]"/>

Which matches any div followed by a table with an empty tbody, and does nothing.

This assumes that your stylesheet is processing elements using a recursive-descent apply-templates operation in the normal way, and that this is the best-match rule for these nodes.

Upvotes: 1

Related Questions