Practical examples of parsing XML data in programming languages

If you work with APIs, sooner or later you’ll run into XML. And when you do, having real, practical examples of parsing XML data in programming languages makes the difference between fumbling with string operations and writing clean, reliable code. In this guide, we’ll walk through concrete examples of parsing XML data in programming languages developers actually use in 2024: Python, JavaScript/TypeScript, Java, C#, PHP, and Go. Along the way, we’ll compare XML parsing to JSON handling, show how modern libraries simplify the work, and call out pitfalls that regularly trip teams up. You’ll see how to load XML from an HTTP API, navigate nested elements, pull attributes, handle namespaces, and convert XML to native data structures. These examples of parsing XML data in programming languages are written with real-world use cases in mind: payment gateways, legacy SOAP services, RSS feeds, and configuration files that stubbornly refuse to move to JSON.
Written by
Jamie
Published

Real-world examples of parsing XML data in programming languages

Before definitions and theory, let’s start where developers actually live: code. Here are real examples of parsing XML data in programming languages you’re likely to use on API projects today.

The sample XML will be a tiny order document returned by a fictional e‑commerce API:

<order id="12345" status="shipped" xmlns:pay="http://payments.example.com">
  <customer>
    <name>Jane Doe</name>
    <email>jane@example.com</email>
  </customer>
  <items>
    <item sku="A100" quantity="2">
      <name>USB-C Cable</name>
      <price currency="USD">9.99</price>
    </item>
    <item sku="B200" quantity="1">
      <name>Wireless Mouse</name>
      <price currency="USD">24.50</price>
    </item>
  </items>
  <pay:transaction id="tx-789" method="card" />
</order>

We’ll keep coming back to this as we walk through specific examples of parsing XML data in programming languages.


Python example of parsing XML data from an API

Python stays popular for API work in 2024 because its XML libraries are straightforward and widely supported.

Using the standard library xml.etree.ElementTree:

import xml.etree.ElementTree as ET

xml_str = open("order.xml", "r", encoding="utf-8").read()
root = ET.fromstring(xml_str)

order_id = root.get("id")
status = root.get("status")

customer_name = root.find("customer/name").text
customer_email = root.find("customer/email").text

items = []
for item_el in root.findall("items/item"):
    items.append({
        "sku": item_el.get("sku"),
        "quantity": int(item_el.get("quantity")),
        "name": item_el.find("name").text,
        "price": float(item_el.find("price").text),
        "currency": item_el.find("price").get("currency"),
    })

print(order_id, status, customer_name, len(items))

For namespaces (like pay:transaction), you pass a mapping:

ns = {"pay": "http://payments.example.com"}
transaction = root.find("pay:transaction", ns)
transaction_id = transaction.get("id")

This is one of the best examples of parsing XML data in programming languages where the standard library is enough for many API use cases. For more advanced needs (validation, XPath 2.0, XSD), teams often use lxml.


JavaScript and TypeScript examples of parsing XML data

On the JavaScript side, parsing XML used to be awkward, but modern tooling has improved the story.

Browser example of parsing XML data

In browsers, you can use DOMParser:

const xmlStr = `...`; // XML from fetch()

const parser = new DOMParser();
const doc = parser.parseFromString(xmlStr, "application/xml");

const order = doc.querySelector("order");
const orderId = order.getAttribute("id");

const name = doc.querySelector("customer > name").textContent;

const items = Array.from(doc.querySelectorAll("items > item")).map(item => ({
  sku: item.getAttribute("sku"),
  quantity: Number(item.getAttribute("quantity")),
  name: item.querySelector("name").textContent,
  price: Number(item.querySelector("price").textContent),
  currency: item.querySelector("price").getAttribute("currency"),
}));

Node.js example of parsing XML data

In Node.js, developers typically avoid manual DOM parsing and convert XML to JSON-like objects. A common 2024 choice is fast-xml-parser:

npm install fast-xml-parser
import { XMLParser } from "fast-xml-parser";

const parser = new XMLParser({
  ignoreAttributes: false,
  attributeNamePrefix: "@_",
});

const xmlStr = await fetchOrderXml();
const obj = parser.parse(xmlStr);

const order = obj.order;
const orderId = order["@_id"];
const status = order["@_status"];

const customerName = order.customer.name;
const firstItemSku = order.items.item[0]["@_sku"];

This pattern—convert XML to a plain object, then work as if it were JSON—is one of the most common examples of parsing XML data in programming languages that are primarily JSON‑centric.


Java examples of parsing XML data in programming languages

Java still powers a huge amount of enterprise APIs and SOAP services, so XML parsing is not going away anytime soon.

DOM-style example of parsing XML data

Using the standard JAXP DOM APIs:

import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);

Document doc = factory.newDocumentBuilder()
    .parse(new File("order.xml"));

elementNormalize(doc);

Element order = (Element) doc.getElementsByTagName("order").item(0);
String orderId = order.getAttribute("id");

Element customer = (Element) order.getElementsByTagName("customer").item(0);
String name = customer.getElementsByTagName("name").item(0).getTextContent();

JAXB / Jakarta XML Binding example

In modern Java (Jakarta EE / Spring Boot), a more natural approach is to bind XML to POJOs:

import jakarta.xml.bind.annotation.*;

@XmlRootElement(name = "order")
@XmlAccessorType(XmlAccessType.FIELD)
public class Order {
    @XmlAttribute
    public String id;

    @XmlElement
    public Customer customer;

    @XmlElementWrapper(name = "items")
    @XmlElement(name = "item")
    public List<Item> items;
}

Then unmarshal:

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Unmarshaller;

JAXBContext ctx = JAXBContext.newInstance(Order.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();

Order order = (Order) unmarshaller.unmarshal(new File("order.xml"));
System.out.println(order.id + " " + order.customer.name);

For teams maintaining large API integrations, this binding approach is one of the best examples of parsing XML data in programming languages in a type‑safe way.


C# and .NET examples of parsing XML data

In the .NET world, XML is deeply integrated, especially in older WCF and SOAP services, configuration files, and some financial APIs.

LINQ to XML example of parsing XML data

LINQ to XML makes querying XML feel like querying in‑memory objects:

using System.Xml.Linq;

var xml = XDocument.Load("order.xml");

var order = xml.Root;
var orderId = (string)order.Attribute("id");

var customerName = (string)order
    .Element("customer")
    .Element("name");

var items = order
    .Element("items")
    .Elements("item")
    .Select(x => new {
        Sku = (string)x.Attribute("sku"),
        Quantity = (int)x.Attribute("quantity"),
        Name = (string)x.Element("name"),
        Price = (decimal)x.Element("price"),
        Currency = (string)x.Element("price").Attribute("currency")
    })
    .ToList();

XmlSerializer example of binding XML to classes

using System.Xml.Serialization;

[XmlRoot("order")]
public class Order {
    [XmlAttribute("id")] public string Id { get; set; }
    public Customer Customer { get; set; }
}

var serializer = new XmlSerializer(typeof(Order));
using var fs = File.OpenRead("order.xml");
var order = (Order)serializer.Deserialize(fs);

These C# patterns are strong examples of parsing XML data in programming languages where static typing and LINQ support make XML far more pleasant than many developers expect.


PHP examples of parsing XML data in legacy and modern APIs

PHP still powers a huge share of the web, and XML shows up in payment gateways, shipping providers, and older SOAP integrations.

SimpleXML example of parsing XML data

SimpleXML gives you a lightweight, almost JSON‑like experience:

$xmlStr = file_get_contents('order.xml');
\(xml = simplexml_load_string(\)xmlStr);

\(orderId = (string)\)xml['id'];
\(customerName = (string)\)xml->customer->name;

$items = [];
foreach (\(xml->items->item as \)item) {
    $items[] = [
        'sku' => (string)$item['sku'],
        'quantity' => (int)$item['quantity'],
        'name' => (string)$item->name,
        'price' => (float)$item->price,
        'currency' => (string)$item->price['currency'],
    ];
}

For heavier workloads, PHP’s XMLReader provides a streaming parser that uses far less memory, which matters when processing large XML feeds like product catalogs or RSS archives.


Go example of parsing XML data with struct tags

Go has a surprisingly clean story for XML thanks to the encoding/xml package.

import (
    "encoding/xml"
    "os"
)

type Order struct {
    XMLName  xml.Name `xml:"order"`
    ID       string   `xml:"id,attr"`
    Status   string   `xml:"status,attr"`
    Customer struct {
        Name  string `xml:"name"`
        Email string `xml:"email"`
    } `xml:"customer"`
}

func main() {
    f, _ := os.Open("order.xml")
    defer f.Close()

    var order Order
    if err := xml.NewDecoder(f).Decode(&order); err != nil {
        panic(err)
    }

    println(order.ID, order.Customer.Name)
}

This Go snippet is a clear example of parsing XML data in programming languages that favor explicit struct tags and compile‑time checks.


XML vs JSON in modern APIs: where XML still matters

JSON dominates new public APIs, but XML is far from dead. In 2024–2025, XML still appears in:

  • Financial and banking integrations using ISO 20022 messages.
  • Healthcare systems and standards like HL7 v3 and some FHIR implementations.
  • Government data portals that publish XML feeds alongside or instead of JSON.
  • Legacy SOAP services that enterprises are reluctant to retire.

For context, the U.S. government’s open data portal still lists datasets in XML formats alongside JSON and CSV options: https://data.gov.

When teams compare JSON vs XML in APIs, the real question is not “which is better” but “which format does this provider actually give us, and how do we parse it safely?” The examples of parsing XML data in programming languages above are exactly the kind of patterns developers rely on when they don’t control the data format.


Common pitfalls when parsing XML from APIs

Even experienced developers get burned by XML quirks. A few patterns show up repeatedly across languages:

Namespaces
That xmlns attribute at the top of a document changes how elements are matched. In Python, Java, and C#, you often have to supply a namespace map or use fully qualified names. Ignoring namespaces is one of the fastest ways to end up with empty query results.

Streaming vs in‑memory parsing
For small payloads, in‑memory DOM parsing is fine. For large responses—think megabyte‑scale medical records or financial transaction batches—streaming parsers (XMLReader in PHP, XmlReader in .NET, xml.Decoder in Go) are safer and more memory‑efficient.

Security and untrusted XML
XXE (XML External Entity) attacks are still a risk if parsers are configured poorly. The OWASP Foundation maintains current guidance on how to harden XML parsing across languages: https://owasp.org. Many modern libraries disable external entity resolution by default, but older enterprise stacks may still need configuration changes.

Validation vs “best effort” parsing
In regulated domains—healthcare, finance, government—schemas (XSD) matter. The U.S. National Library of Medicine, for example, publishes XML schemas for clinical and research data at https://www.nlm.nih.gov. In those environments, examples of parsing XML data in programming languages almost always include schema validation as part of the pipeline.


How to choose an XML parsing approach in your language

Looking across these examples of parsing XML data in programming languages, a few patterns help guide architecture decisions:

  • If the XML is small and you just need a handful of fields, DOM‑style or SimpleXML‑style parsing is usually fast to implement.
  • If you own the data model and want type safety, binding libraries (JAXB/Jakarta in Java, XmlSerializer in .NET, encoding/xml in Go) pay off quickly.
  • If you come from a JSON‑first background (Node.js, front‑end JavaScript), using a library that converts XML to a plain object lets you reuse your existing patterns.
  • If you are processing huge feeds—think gigabytes of log exports or medical records—streaming parsers protect you from memory exhaustion and keep performance predictable.

In other words, the best examples of parsing XML data in programming languages are the ones that match the size, sensitivity, and lifetime of your integration.


FAQ: examples of parsing XML data in programming languages

Q: Can you give a simple example of parsing XML data from an HTTP API?
Yes. In Python, you might use requests plus ElementTree:

import requests
import xml.etree.ElementTree as ET

resp = requests.get("https://api.example.com/orders/12345")
root = ET.fromstring(resp.text)
status = root.get("status")

This pattern mirrors many real examples of parsing XML data in programming languages that fetch from REST or SOAP endpoints.

Q: What is an example of converting XML to JSON for easier handling?
In Node.js, a common pattern is to parse XML into a JavaScript object, then JSON.stringify it:

import { XMLParser } from "fast-xml-parser";

const parser = new XMLParser({ ignoreAttributes: false });
const xmlStr = await fetchXml();
const obj = parser.parse(xmlStr);
const json = JSON.stringify(obj);

Q: Are there good examples of parsing XML in strongly typed languages like Java or C#?
Yes. The JAXB/Jakarta binding example in Java and the XmlSerializer example in C# above both show how to map XML elements and attributes directly to typed classes. These are widely used in enterprise integrations.

Q: How do I safely parse untrusted XML from external partners?
Look up the security recommendations for your language’s XML libraries and disable external entity resolution, DTD processing, and other risky features. OWASP’s XML external entity prevention cheat sheet at https://owasp.org is a good starting point.

Q: Where can I see real examples of XML used in public data?
Government and research portals are rich sources. The U.S. government’s data portal at https://www.data.gov and the National Library of Medicine’s resources at https://www.nlm.nih.gov both publish XML datasets and schemas that you can download and practice parsing.

Explore More Data Formats: JSON vs XML in APIs

Discover more examples and insights in this category.

View All Data Formats: JSON vs XML in APIs