Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Access XML Data via JavaScript ?
Next article icon

JavaScript- Read CDATA in XML

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

CDATA sections in XML are used to include text that shouldn't be parsed by the XML parser, such as special characters or reserved words. You can read CDATA content in JavaScript by parsing the XML and accessing the content.

Parse XML and Read CDATA

In this method, we parse an XML string using the DOMParser and access the content inside the CDATA section. CDATA sections are used to include raw text without being parsed by the XML parser.

HTML
<!DOCTYPE html> <html lang="en"> <body>     <script>         const xmlString = `       <note>         <to>John</to>         <from>Jane</from>         <message><![CDATA[Hello, this is a CDATA section!]]></message>       </note>     `;         const parser = new DOMParser();         const xmlDoc = parser.parseFromString(xmlString, "text/xml");          const cdataContent = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;          console.log(cdataContent);       // Output: Hello, this is a CDATA section!     </script> </body> </html> 

Fetch XML File and Read CDATA

In this method, you load an external XML file using the fetch API and then parse the XML to extract the content inside the CDATA section. This is useful when you need to work with XML data hosted remotely.

HTML
<!DOCTYPE html> <html lang="en"> <body>     <script>         fetch("example.xml")              .then(response => response.text())             .then(data => {                 const parser = new DOMParser();                 const xmlDoc = parser.parseFromString(data, "text/xml");                  const cdataContent = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;                 console.log(cdataContent);              })             .catch(error => console.error("Error fetching XML:", error));     </script> </body> </html> 

Use XPath to Locate CDATA

In this method, XPath is used to directly locate and extract the content of the CDATA section. XPath allows you to query XML documents with more precision, making it easier to extract specific elements or text.

HTML
<!DOCTYPE html> <html lang="en"> <body>     <script>         const xmlString = `       <note>         <to>John</to>         <from>Jane</from>         <message><![CDATA[Hello, this is a CDATA section!]]></message>       </note>     `;         const parser = new DOMParser();         const xmlDoc = parser.parseFromString(xmlString, "text/xml");          const xpathResult = xmlDoc.evaluate("//message/text()", xmlDoc, null, XPathResult.STRING_TYPE, null);         console.log(xpathResult.stringValue);      </script> </body> </html> 

Next Article
How to Access XML Data via JavaScript ?

A

anujpaz9pe
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to Create XML in JavaScript ?
    In JavaScript, XML documents can be created using various approaches. You can define elements, attributes, and content to structure the XML data, and then serialize it into a string for use or storage. There are several approaches to creating XML in JavaScript which are as follows: Table of Content
    2 min read
  • How to Parse XML in JavaScript?
    Parsing XML data is important because it allows JavaScript applications to extract structured information from XML documents. We will explore two different approaches to Parse XML in JavaScript. Below are the approaches to parsing XML in JavaScript: Table of Content Using DOM ParserUsing xml2js Libr
    2 min read
  • How to Access XML Data via JavaScript ?
    XML stands for Extensible Markup Language. It is a popular format for storing and exchanging data on the web. It provides a structured way to represent data that is both human-readable and machine-readable. There are various approaches to accessing XML data using JavaScript which are as follows: Tab
    2 min read
  • How to Validate XML in JavaScript ?
    Validation of XML is important for ensuring data integrity and adherence to XML standards in JavaScript. There are various approaches available in JavaScript using which validation of the XML can be done which are described as follows: Table of Content Using DOM ParserUsing Tag MatchingUsing DOM Par
    2 min read
  • How to Load XML from JavaScript ?
    Loading XML data into JavaScript is a common task, whether it's for parsing user input or fetching data from a server. The below-listed approaches can be used to load XML from JavaScript. Table of Content Parsing XML String DirectlyFetching XML Data from an External SourceParsing XML in Node.js usin
    4 min read
  • How to Validate XML against XSD in JavaScript ?
    XML (Extensible Markup Language) is a widely used format for storing and exchanging structured data. XSD (XML Schema Definition) is a schema language used to define the structure, content, and data types of XML documents. Validating XML against XSD ensures that the XML document conforms to the speci
    4 min read
  • How to Convert XML to JSON in JavaScript?
    To convert XML to JSON in JavaScript, various methods and libraries and be used. Here, we use xml-js library that provides xml2json function to convert XML to JSON data. It takes XML data as input and gives the JSON objects as output. We can also use the DOMParser from the xmldom package to convert
    2 min read
  • How to Loop through XML in JavaScript ?
    In JavaScript, looping over XML data is important for processing and extracting information from structured XML documents. Below is a list of methods utilized to loop through XML. Table of Content Using for loop with DOMParser and getElementsByTagNameUsing Array.from with DOMParser and childNodesUsi
    2 min read
  • How to Fetch XML with Fetch API in JavaScript ?
    The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods. These are the following meth
    3 min read
  • XML - CDATA Sections
    CDATA sections are a mechanism in XML for handling character data that might otherwise be misinterpreted by the XML parser. CDATA stands for Character Data. These sections include blocks of text within an XML document that the parser should treat literally, without interpreting any characters as XML
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences