function processSitemap() {
    // ===== CONFIG =====
    var kbSysId = "ae26315ec325aa50fd309bbc7a01317b"; // sys_id of the Knowledge Base
    var escBase = gs.getProperty('glide.servlet.uri'); // EXACT base URL you want (no trailing slash)
    var useDisplayTimezoneForLastmod = false; // see note below
    function xmlEscape(s) {
        if (s == null) return "";
        return ("" + s)
            .replace(/&/g, "&")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&apos;");
    }

    function toDateYYYYMMDD(dateTimeStr) {
        // "YYYY-MM-DD HH:mm:ss" -> "YYYY-MM-DD"
        if (!dateTimeStr) return "";
        return ("" + dateTimeStr).substring(0, 10);
    }
    // ===== QUERY PUBLISHED ARTICLES =====
    var grKB = new GlideRecord("kb_knowledge");
    grKB.addQuery("kb_knowledge_base", kbSysId);
    grKB.addQuery("workflow_state", "published");
    // Include only published articles where Valid To date is empty (no expiry)
    // OR Valid To date is after the end of today (i.e., not expired yet).
    grKB.addEncodedQuery("valid_toISEMPTY^ORvalid_to>javascript&colon;gs.endOfToday()");
    grKB.orderBy("number");
    grKB.query();
    // ===== BUILD ONLY <url> ENTRIES =====
    var urlLines = [];
    while (grKB.next()) {
        var number = grKB.getValue("number"); // e.g. KB0011578
        var loc = escBase + "esc?id=kb_article&sysparm_article=" + number;
        var lastmodRaw = useDisplayTimezoneForLastmod ?
            grKB.getDisplayValue("sys_updated_on") :
            grKB.getValue("sys_updated_on");
        var lastmod = toDateYYYYMMDD(lastmodRaw);
        urlLines.push("   <url>");
        urlLines.push("      <loc>" + xmlEscape(loc) + "</loc>");
        if (lastmod) {
            urlLines.push("      <lastmod>" + xmlEscape(lastmod) + "</lastmod>");
        }
        urlLines.push("   </url>");
    }
    // Return the concatenated <url> entries (NOT the urlset wrapper)
    return urlLines.join("\n");
}
// If your platform expects the function to be invoked:
processSitemap();

 

With this extra query only knowledge articles that have a Valid To date set after today, or where the Valid To date is empty (no expiry) will be selected, to make sure only working links will be presented in the Sitemap file.