Ogni servizio SOAP che hai toccato, ogni feed RSS che hai consumato, ogni SVG che hai manipolato — sono tutti XML. JavaScript ha due modi integrati per analizzarlo nel browser, e una solida libreria npm per Node.js. La parte difficile non è l'analisi in sé; è navigare il DOM risultante, gestire i namespace e non essere colti di sorpresa dalle peculiarità che fanno inciampare tutti la prima volta. Vediamo i pattern reali.

DOMParser — Analisi di XML nel Browser

L'API integrata del browser DOMParser converte una stringa XML in un documento DOM. Usa il tipo MIME 'application/xml' (non 'text/html') in modo che il parser applichi le regole XML rigorose:

js
const xmlString = `<?xml version="1.0" encoding="UTF-8"?>
<library>
  <book isbn="978-0-13-110362-7">
    <title>The C Programming Language</title>
    <authors>
      <author>Brian W. Kernighan</author>
      <author>Dennis M. Ritchie</author>
    </authors>
    <year>1988</year>
    <price currency="USD">45.99</price>
  </book>
  <book isbn="978-0-201-63361-0">
    <title>The Pragmatic Programmer</title>
    <authors>
      <author>Andrew Hunt</author>
      <author>David Thomas</author>
    </authors>
    <year>1999</year>
    <price currency="USD">52.00</price>
  </book>
</library>`;

const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, 'application/xml');

// Controlla sempre gli errori di analisi prima
const parseError = doc.querySelector('parsererror');
if (parseError) {
  throw new Error('XML parse failed: ' + parseError.textContent);
}

console.log(doc.documentElement.tagName); // library
Controlla sempre parsererror. A differenza di JSON.parse() che solleva un'eccezione, DOMParser restituisce un documento contenente un elemento <parsererror> quando l'analisi fallisce — non solleva un'eccezione. Se salti il controllo degli errori, opererai silenziosamente su un documento malformato e otterrai risultati confusi a valle.

Navigazione del DOM — getElementsByTagName vs querySelector

Una volta ottenuto un documento analizzato, hai due API principali per trovare gli elementi. Entrambe funzionano, ma hanno punti di forza diversi:

js
// getElementsByTagName — restituisce un HTMLCollection live
const books = doc.getElementsByTagName('book');
console.log(books.length); // 2

// querySelector / querySelectorAll — sintassi CSS selector, restituisce NodeList
const firstTitle = doc.querySelector('title').textContent;
console.log(firstTitle); // The C Programming Language

// Ottieni tutti i titoli
const titles = [...doc.querySelectorAll('title')].map(el => el.textContent);
console.log(titles);
// ['The C Programming Language', 'The Pragmatic Programmer']

// Lettura degli attributi
const firstBook = doc.querySelector('book');
const isbn = firstBook.getAttribute('isbn');
console.log(isbn); // 978-0-13-110362-7

// Lettura dell'attributo currency dal prezzo
const priceEl = firstBook.querySelector('price');
console.log(priceEl.textContent);           // 45.99
console.log(priceEl.getAttribute('currency')); // USD

Preferisco querySelector per le ricerche mirate — la sintassi CSS selector è familiare e concisa. Usa getElementsByTagName quando hai bisogno di tutti gli elementi con un dato tag e vuoi una collezione live (anche se in pratica, uno spread di NodeList è di solito più pulito).

Estrazione di Dati Strutturati — Un Pattern Pratico

Ecco come mappare un documento XML in un array JavaScript pulito di oggetti — il pattern che userai quando consumi una risposta XML da un'API reale:

js
function parseLibraryXml(xmlString) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(xmlString, 'application/xml');

  if (doc.querySelector('parsererror')) {
    throw new Error('Invalid XML');
  }

  return [...doc.querySelectorAll('book')].map(book => ({
    isbn: book.getAttribute('isbn'),
    title: book.querySelector('title').textContent.trim(),
    authors: [...book.querySelectorAll('author')].map(a => a.textContent.trim()),
    year: parseInt(book.querySelector('year').textContent, 10),
    price: {
      amount: parseFloat(book.querySelector('price').textContent),
      currency: book.querySelector('price').getAttribute('currency')
    }
  }));
}

const books = parseLibraryXml(xmlString);
console.log(books[0].title);          // The C Programming Language
console.log(books[0].authors);        // ['Brian W. Kernighan', 'Dennis M. Ritchie']
console.log(books[0].price.amount);   // 45.99

Gestione di XML con Namespace

I namespace sono il punto dove la maggior parte degli sviluppatori si blocca. Le risposte SOAP, i feed Atom e SVG usano tutti namespace XML — e un semplice querySelector('body') restituirà null su un documento SOAP perché l'elemento è in realtà soap:Body. Ecco come gestirlo correttamente:

js
const soapResponse = `<?xml version="1.0"?>
<soap:Envelope
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:m="http://www.example.com/orders">
  <soap:Header/>
  <soap:Body>
    <m:GetOrderResponse>
      <m:OrderId>ORD-5521</m:OrderId>
      <m:Status>Shipped</m:Status>
      <m:Total currency="EUR">289.50</m:Total>
    </m:GetOrderResponse>
  </soap:Body>
</soap:Envelope>`;

const parser = new DOMParser();
const doc = parser.parseFromString(soapResponse, 'application/xml');

// Opzione 1: getElementsByTagNameNS — URI namespace esplicito
const SOAP_NS = 'http://schemas.xmlsoap.org/soap/envelope/';
const ORDER_NS = 'http://www.example.com/orders';

const body = doc.getElementsByTagNameNS(SOAP_NS, 'Body')[0];
const orderId = doc.getElementsByTagNameNS(ORDER_NS, 'OrderId')[0].textContent;
const status = doc.getElementsByTagNameNS(ORDER_NS, 'Status')[0].textContent;

console.log(orderId); // ORD-5521
console.log(status);  // Shipped

// Opzione 2: XPath con namespace resolver (più flessibile)
function nsResolver(prefix) {
  const namespaces = {
    soap: 'http://schemas.xmlsoap.org/soap/envelope/',
    m: 'http://www.example.com/orders'
  };
  return namespaces[prefix] || null;
}

const xpathResult = doc.evaluate(
  '//m:OrderId',
  doc,
  nsResolver,
  XPathResult.STRING_TYPE,
  null
);
console.log(xpathResult.stringValue); // ORD-5521

Query XPath con evaluate()

XPath è un linguaggio di query per documenti XML. Il browser lo espone tramite document.evaluate(). È più potente dei selettori CSS per XML — puoi fare query per valore di attributo, posizione, contenuto testuale e ascendenza. Consulta la documentazione MDN su XPath per la sintassi completa delle espressioni:

js
// Usando il documento XML della libreria precedente
function xpath(doc, expression, contextNode = doc) {
  const result = doc.evaluate(
    expression,
    contextNode,
    null,  // namespace resolver — null per XML senza namespace
    XPathResult.ANY_TYPE,
    null
  );
  return result;
}

// Ottieni tutti i titoli dei libri
const titlesResult = xpath(doc, '//book/title');
const titles = [];
let node;
while ((node = titlesResult.iterateNext())) {
  titles.push(node.textContent);
}
console.log(titles);
// ['The C Programming Language', 'The Pragmatic Programmer']

// Ottieni il libro con un ISBN specifico
const bookResult = doc.evaluate(
  '//book[@isbn="978-0-13-110362-7"]/title',
  doc, null,
  XPathResult.STRING_TYPE,
  null
);
console.log(bookResult.stringValue); // The C Programming Language

// Ottieni libri con prezzo superiore a $50
const expensiveResult = xpath(doc, '//book[price > 50]/title');
let expensiveNode;
while ((expensiveNode = expensiveResult.iterateNext())) {
  console.log(expensiveNode.textContent); // The Pragmatic Programmer
}

Node.js — fast-xml-parser (La Scelta Migliore)

Node.js non ha DOMParser. Hai due opzioni: usare l'approccio SAX basato su stream integrati node:stream (laborioso), o usare fast-xml-parser (la scelta giusta per la maggior parte dei casi d'uso). È veloce, senza dipendenze e restituisce oggetti JavaScript semplici:

bash
npm install fast-xml-parser
js
import { XMLParser } from 'fast-xml-parser';

const xmlString = `<?xml version="1.0"?>
<library>
  <book isbn="978-0-13-110362-7">
    <title>The C Programming Language</title>
    <year>1988</year>
    <price currency="USD">45.99</price>
  </book>
  <book isbn="978-0-201-63361-0">
    <title>The Pragmatic Programmer</title>
    <year>1999</year>
    <price currency="USD">52.00</price>
  </book>
</library>`;

const parser = new XMLParser({
  ignoreAttributes: false,     // includi gli attributi XML
  attributeNamePrefix: '@_',   // prefissa gli attributi per distinguerli dagli elementi
  isArray: (tagName) => tagName === 'book'  // tratta sempre <book> come array
});

const result = parser.parse(xmlString);
const books = result.library.book;

books.forEach(book => {
  console.log(book.title);       // The C Programming Language
  console.log(book['@_isbn']);   // 978-0-13-110362-7
  console.log(book.price['#text']);       // 45.99
  console.log(book.price['@_currency']); // USD
});
L'opzione isArray è fondamentale. Se il tuo XML ha un elemento lista che a volte contiene un elemento e a volte molti, fast-xml-parser ti darà un oggetto per un elemento e un array per molti. L'opzione isArray impone un comportamento array coerente per i tag nominati — usala sempre per elementi che sai possano ripetersi.

Gestione degli Errori in Node.js

js
import { XMLParser, XMLValidator } from 'fast-xml-parser';

function parseXmlSafely(xmlString) {
  // Valida prima — restituisce true o un oggetto errore
  const validation = XMLValidator.validate(xmlString);
  if (validation !== true) {
    throw new Error(`Invalid XML: ${validation.err.msg} at line ${validation.err.line}`);
  }

  const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' });
  return parser.parse(xmlString);
}

try {
  const data = parseXmlSafely(xmlString);
  console.log(data);
} catch (err) {
  console.error('XML parsing failed:', err.message);
}

Strumenti Correlati

Quando lavori con XML in progetti JavaScript: Formattatore XML per formattare risposte minificate, Validatore XML per verificare il formato corretto prima dell'analisi, Tester XPath XML per sperimentare con query XPath, e XML in JSON se vuoi convertire a una struttura più semplice.

Conclusioni

Nel browser, DOMParser con 'application/xml' è la scelta principale — ricorda solo di controllare parsererror. Per XML con namespace, usa getElementsByTagNameNS o XPath con un namespace resolver. In Node.js, fast-xml-parser ti fornisce oggetti JavaScript puliti senza l'overhead del DOM. I pattern qui coprono il 95% degli scenari reali di analisi XML — risposte SOAP, feed RSS, file di configurazione e altro ancora.