XQuery: Deleting Empty Nodes From XML Document

  • Hi peops,

    I am new to XQuery and have a problem. I want to delete a child element (in this case called 'step') if and only if it is empty i.e. <step/>. So if there are 3 step elements and the last 2 are empty, then only these 2 elements should be deleted. In effect, the position of this child element is irrelevant. But at moment, I can only delete either all step elements or specified ones. I want to be able to delete the step child element regardless of it's ordinal position. Help any one...please? :unsure:

    Below is the sample document and code.

    declare @xdata as xml = '

    <root>

    <location locationid="10">

    <step>Alpha</step>

    <step />

    <step>Beta</step>

    </location>

    <location locationid="20">

    <step />

    <step />

    <step>Gamma</step>

    </location>

    <location locationid="30">

    <step />

    <step>prime</step>

    </location>

    </root>

    '

    [p]set @xdata.modify('delete //step[fn:empty(.) = xs:boolean("true")]')[/p]

    Many Thanks.

  • Hi.. I would use something like the following. This is checking to see if the text node is empty or not in the predicate.:

    set @xdata.modify('delete //step[empty(text())]')

  • Many thanks arthurolcot, it worked! I appreciate your effort.

    Nice one and have a lovely weekend! 😀

    Best Regards.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply