Search code examples
xquerymarklogic

How to find self closing tag using XQuery


I need to find Self closing tag XML in using XQuery,

for example I have two kind of XML are available.

**Example 1** : fn:matches(<root><a>Eng</a><b>maths</b></root>//b ,<b/>);
answer : true

**Example 2** : fn:matches(<root><a>Eng</a><b/></root>//b ,<b/>);
answer : true

The above example both are getting results are true but my expectation is first one XML have no self-closing tag so it's getting false so it can any possible ? please help.


Solution

  • I think you misunderstood the usage of fn:matches. You can find the official specification here: https://www.w3.org/TR/xquery-operators/#func-matches. But in short, it is a means to match a string (first argument) against a regular expression (second argument).

    You are providing element nodes. These get cast to strings first, so you are effectively running:

    fn:matches("maths", "")
    

    Which indeed returns true. You might be better off using fn:deep-equal.

    Then again, that will not help distinguish <b></b> versus <b/> since those are considered identical in XML processors. If you are simply looking for empty elements, you can do:

    let $xml := <root><a>Eng</a><b>maths</b></root>
    return $xml//b[not(. = '')]
    

    or:

    let $xml := <root><a>Eng</a><b>maths</b></root>
    return $xml//b[empty(node())]
    

    HTH!