Javascript function to convert sitemap.xml to array

CK CK 3788 
Created at
Updated at  
603 0 0

A sitemap is a file or document that lists all the URLs (web addresses) of a website, along with additional metadata about each URL. It is primarily used to inform search engines about the structure of the site and to help them crawl it more effectively. Sitemaps can be beneficial for both SEO (Search Engine Optimization) and user experience. 

 

Benefits of Sitemaps

  • Improved Indexing: Sitemaps help search engines discover and index all the important pages on a website, ensuring that they appear in search results.
  • Content Updates: By including <lastmod> tags, webmasters can inform search engines when a page was last updated, prompting them to crawl it more frequently.
  • Prioritization: The <priority> tag allows webmasters to indicate the importance of certain pages relative to others.
  • User Navigation: HTML sitemaps provide a straightforward way for visitors to find content on the site.

 

To convert the URLs from a sitemap.xml into an array in JavaScript, you can use the fetch API combined with DOMParser. Below is a complete example that demonstrates how to achieve this:

function SITEMAP_TO_ARRAY(sitemap_xml) {
	try {
		// Parse the XML string into a DOM
		const parser = new DOMParser();
		const xmlDoc = parser.parseFromString(sitemap_xml, "application/xml");

		// Extract the <url> elements
		const urlElements = xmlDoc.getElementsByTagName("url");
		const sitemapData = [];

		// Loop through each <url> and extract <loc> and <lastmod>
		for (let i = 0; i < urlElements.length; i++) {
			const loc = urlElements[i].getElementsByTagName("loc")[0]?.textContent || null;
			const lastmod = urlElements[i].getElementsByTagName("lastmod")[0]?.textContent || null;
			const changefreq = urlElements[i].getElementsByTagName("changefreq")[0]?.textContent || null;
			const priority = urlElements[i].getElementsByTagName("priority")[0]?.textContent || null;

			if (loc) {
				sitemapData.push({ "loc":loc, "lastmod":lastmod, "changefreq":changefreq, "priority":priority });
			}
		}

		return sitemapData;  // Return the array of URLs and last modified dates
	} catch (error) {
		console.error("Error fetching or parsing the sitemap:", error);
		return [];  // Return an empty array in case of error
	}
}


Associated Data for Sitemap.xml to Array Conversion:

  • Purpose: The provided JavaScript function `SITEMAP_TO_ARRAY` aims to extract URLs and associated metadata (last modified date, change frequency, and priority) from a sitemap.xml file and store them in a JavaScript array.
  • Core Functionality:
    • DOMParser: The function utilizes the DOMParser to parse the XML string representing the sitemap.xml file into a DOM (Document Object Model) representation.
    • URL Extraction: It iterates through all `` elements within the XML structure, extracting the `loc` (URL), `lastmod` (last modified date), `changefreq` (change frequency), and `priority` values.
    • Data Organization: The extracted data is then organized into an array of objects, where each object represents a single URL and its corresponding metadata.
  • Error Handling:
    • The code includes a try-catch block to handle potential errors during the XML parsing or fetching process. If an error occurs, it logs the error and returns an empty array.
  • Applications:
    • This function can be useful for various SEO-related tasks, such as:

* Analyzing website structure and content updates.
* Building custom crawlers or indexing tools.
* Performing site audits and identifying issues.

  • Additionally, the extracted data can be used for building interactive sitemaps, dashboards, or visualizations.
  • Additional Notes:
    • The function assumes that the input `sitemap_xml` is a valid XML string representing a sitemap.xml file.
    • This approach relies on the standard sitemap.xml structure and may need adjustments for sitemaps with non-standard formats.
    • For handling large sitemaps or remote sitemaps, consider using asynchronous approaches (e.g., promises or async/await) for fetching and parsing the XML.
Tags DOMParser getElementsByTagName sitemap.xml Facebook X
Comments 0
Similar posts
  1. JavaScript Code to Get the Page Title
    340
  1. A simple JavaScript snippet to copy a string to the clipboard
    1,058
  2. Dynamic JSON Editor based in HTML/JavaScript
    514
  3. How to post content (image or video) to Instagram using the Instagram Graph API
    6,412
  4. Font name correctly having the same width space
    1,229
  5. JavaScript Algorithms
    722
  6. GraphQL Tutorial on CentOS 7: From Installation to Deployment
    564
  7. Capture all browser console logs including errors for debugging
    2,192
  8. Simple asynchronous/synchronous $.ajax() example using jQuery to make an HTTP GET request
    863
  9. JavaScript Code to Get Page Keywords
    353
  10. What is OpenGraph?
    367
  11. What is Twitter Cards?
    405
  12. Code to Extract the Site Thumbnail Image for Twitter or Facebook
    396
  13. JavaScript Code to Get Meta Description from HTML
    398
  14. Javascript code to extract favicon URL
    405
  15. RSS to Array in JavaScript
    2,169
  16. Understanding Elasticsearch from Installation to Trouble Shooting
    915
  17. IndexNow for better SEO
    321
  18. Enhancing SEO for Single Page Applications: Implementing Dynamic URL Updates
    1,043
  19. Method to ignore JavaScript Errors globally instead of try... catch for each of cases
    973
  20. Method to catch the browser console log and errors for remote web debugging
    2,191
  21. Atlassian Jira Ticket API Response Example
    2,807
  22. Three different type of Word-Wrap options in HTML CSS
    1,189
  23. JavaScript code to load XML Document
    604
  24. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    599
  25. Equal Height Blocks in Bootstrap with JavaScript
    713
  26. Copy text to clipboard in Javascript
    1,717
  27. To block copy & paste on your blog content
    905
  28. Shake your browser window by Javascript
    939
  29. Photoshop script programming in Javascript
    533
  30. To compare two HTML tables on web page in real time
    517
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,255
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233