Search code examples
xquerymarklogic

Marklogic - How to remove new line char issue in XQuery


How to removing the new line character .

Sample Code.

    let $b := <root><title>Fees • Levies<?brk type="line"?>
    Other file</title></root>
    return replace($b//title/text(),'\n','')

Expected Output :
Fees • Levies Other file

Solution

  • A few options I can think of:

    fn:replace() - but you have to account for both possible chars

    let $b := <root><title>Fees • Levies<?brk type="line"?>
        Other file</title></root>
    return fn:replace(fn:data($b//title), '(\r?\n|\r)', '')
    

    But this can leave you with extra whitespace depending on how it was created and formatted, Therefore, you may also prefer to clean up the whitespace and the newline at once using fn:normalize-space()

    let $b := <root><title>Fees • Levies<?brk type="line"?>
        Other file</title></root>
    return fn:normalize-space(fn:data($b//title))
    

    You may also note that I used fn:data(). This was out of habit. However, there is a great blogpost here on the subject of text, string, data.