Home > Web Front-end > JS Tutorial > How Can I Parse XML Data in JavaScript Without Using External Libraries?

How Can I Parse XML Data in JavaScript Without Using External Libraries?

Barbara Streisand
Release: 2024-12-01 01:53:12
Original
169 people have browsed it

How Can I Parse XML Data in JavaScript Without Using External Libraries?

Parse XML with JavaScript

Parsing XML involves converting XML data into a format that can be processed by JavaScript code. To do this without external frameworks like jQuery, the DOM (Document Object Model) can be utilized.

If the XML is stored in a string variable named txt, its structure could resemble the following:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>
Copy after login

To parse this XML, follow these steps:

// Create a new DOM parser
var parser = new DOMParser();

// Parse the XML string into a DOM object
var xmlDoc = parser.parseFromString(txt, "text/xml");
Copy after login

With the DOM object available, specific XML elements can be accessed and their values retrieved:

// Get the street number
var streetNumber = xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

// Get the street name
var street = xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

// Get the postal code
var postalcode = xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;
Copy after login

XML with namespace prefixes can also be parsed using this method, provided that the browser supports namespace prefixes. The namespace prefixes can be accessed without the prefix in the JavaScript code.

The above is the detailed content of How Can I Parse XML Data in JavaScript Without Using External Libraries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template