0

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>
1
  • 1
    You're expected to show an attempt. Hint: Add to the identity transform two templates that suppress (a) div elements followed by a table element that contains an empty tbody element and (b) such table elements themselves. Commented Dec 5, 2021 at 0:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Michael, I can not edit your answer, but it has missing one right bracket at the end.
Edit applied, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.