Rust

Parse XML in Rust with quick-xml

Attributes, text, repeated elements, namespaces and CDATA, with the same structs you already know

Published: November 2026 • 10 min read

New services talk JSON, but the billing system, the HLR export or the SOAP endpoint you've been asked to integrate with still sends XML. If you have read the JSON in Rust with serde article, the good news is that you already know most of what you need. XML just has a few more places for data to hide: attributes, the text inside an element, wrapper elements around lists, namespaces and CDATA.

The crate to reach for is quick-xml. It has a serde layer, so you derive Deserialize on a struct like you would for JSON, and a low-level event reader for files too big to hold in memory. Everything below uses the same subscriber record as the JSON article, and every snippet was compiled and run with the output pasted from the terminal.

You will be writing a few small structs that nest inside each other. If that part still feels shaky, this Rust tutorial on structs is a quick refresher.

Add quick-xml with the serialize feature

The serde support in quick-xml sits behind a feature flag called serialize. Leave it off and quick_xml::de simply doesn't exist, and you get an "unresolved import quick_xml::de" error that doesn't mention features at all.

TOML
[dependencies]
quick-xml = { version = "0.42.0", features = ["serialize"] }
serde = { version = "1.0.229", features = ["derive"] }

quick-xml is still on 0.x and its API changes between minor versions. The code here is written against 0.42, so if you copy an older answer from the internet and it doesn't compile, check the version first.

Attributes, element text and lists

Here is our subscriber as XML. Look at where each value lives, because that decides how you write the struct. id and status are attributes. plan has both an attribute and text. The sectors sit inside a wrapper element.

XML
<?xml version="1.0" encoding="UTF-8"?>
<subscriber id="SUB-20417" status="active">
  <name>Ingrid Hallström</name>
  <msisdn>+46701234567</msisdn>
  <iccid>8901240544102066246</iccid>
  <plan tier="premium">Unlimited 5G</plan>
  <dataUsageGb>42.7</dataUsageGb>
  <roaming>false</roaming>
  <sectors>
    <sector>STO-114</sector>
    <sector>STO-118</sector>
    <sector>UPP-022</sector>
  </sectors>
</subscriber>
Rust
use quick_xml::de::from_str;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subscriber {
    #[serde(rename = "@id")]
    id: String,
    #[serde(rename = "@status")]
    status: String,
    name: String,
    msisdn: String,
    iccid: u64,
    plan: Plan,
    data_usage_gb: f64,
    roaming: bool,
    sectors: Sectors,
}

#[derive(Debug, Deserialize)]
struct Plan {
    #[serde(rename = "@tier")]
    tier: String,
    #[serde(rename = "$text")]
    name: String,
}

#[derive(Debug, Deserialize)]
struct Sectors {
    #[serde(rename = "sector")]
    items: Vec<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let xml = std::fs::read_to_string("subscriber.xml")?;
    let sub: Subscriber = from_str(&xml)?;
    println!("{sub:#?}");
    Ok(())
}
Subscriber {
    id: "SUB-20417",
    status: "active",
    name: "Ingrid Hallström",
    msisdn: "+46701234567",
    iccid: 8901240544102066246,
    plan: Plan {
        tier: "premium",
        name: "Unlimited 5G",
    },
    data_usage_gb: 42.7,
    roaming: false,
    sectors: Sectors {
        items: [
            "STO-114",
            "STO-118",
            "UPP-022",
        ],
    },
}

Three conventions carry the whole thing. A field name matches a child element. A name starting with @ matches an attribute. And $text is the text directly inside the element, which is how Plan gets both the tier attribute and the words "Unlimited 5G". These are ordinary serde attributes; quick-xml just gives the @ and $ prefixes a meaning.

The Sectors struct is the part people trip over. In JSON, sectors was just an array. In XML there is a <sectors> element holding several <sector> elements, and serde needs a struct for each level. Point a Vec<String> straight at sectors and you get an error instead of the three IDs you expected.

Also notice that iccid and roaming are typed. In XML everything is text, but serde parses the text into the field's type, so the 19-digit ICCID lands in a u64 exactly, and a typo in the boolean is an error instead of a string you check later. For anything with more than a handful of elements, paste a sample into the XML to Rust converter and start from the structs it writes.

Optional elements and repeated elements without a wrapper

Plenty of XML repeats an element directly, with no wrapper, and leaves optional elements out entirely. Here is that shape, read with one struct:

Rust
use quick_xml::de::from_str;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Subscriber {
    #[serde(rename = "@id")]
    id: String,
    name: String,
    // <email> may not be there at all
    email: Option<String>,
    // no <sector> elements means an empty list, not an error
    #[serde(rename = "sector", default)]
    sectors: Vec<String>,
}

fn main() -> Result<(), quick_xml::DeError> {
    let with_sectors = r#"<subscriber id="SUB-20417">
  <name>Ingrid Hallström</name>
  <sector>STO-114</sector>
  <sector>STO-118</sector>
</subscriber>"#;

    let without = r#"<subscriber id="SUB-20418">
  <name>Maeve Lindqvist</name>
  <email>[email protected]</email>
</subscriber>"#;

    for xml in [with_sectors, without] {
        let sub: Subscriber = from_str(xml)?;
        println!("{sub:?}");
    }
    Ok(())
}
Subscriber { id: "SUB-20417", name: "Ingrid Hallström", email: None, sectors: ["STO-114", "STO-118"] }
Subscriber { id: "SUB-20418", name: "Maeve Lindqvist", email: Some("[email protected]"), sectors: [] }

Here rename = "sector" is the important bit. The field is called sectors in Rust, but each element in the XML is a singular <sector>, and serde collects all of them into the Vec. The default turns "none at all" into an empty list.

One surprise with Option: an element that is present but empty, like <email/>, gives you Some(""), not None. Only a missing element is None. If your source system writes empty tags for "no value", add a .filter(|s| !s.is_empty()) after parsing.

Namespaces and prefixed names

SOAP responses and vendor exports often put every element under a prefix like tel:. The tempting move is to write #[serde(rename = "tel:name")]. Don't. I tried, and the result was missing field `tel:name`, because the deserializer matches on the local name and ignores the prefix. Plain field names just work:

Rust
use quick_xml::de::from_str;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Subscriber {
    #[serde(rename = "@id")]
    id: String,
    name: String,
    iccid: u64,
}

fn main() -> Result<(), quick_xml::DeError> {
    let xml = r#"<tel:subscriber xmlns:tel="urn:example:telecom:1.0" id="SUB-20417">
  <tel:name>Ingrid Hallström</tel:name>
  <tel:iccid>8901240544102066246</tel:iccid>
</tel:subscriber>"#;

    let sub: Subscriber = from_str(xml)?;
    println!("{sub:?}");
    Ok(())
}
Subscriber { id: "SUB-20417", name: "Ingrid Hallström", iccid: 8901240544102066246 }

The catch is the flip side of the convenience. The serde layer doesn't check which XML namespace an element belongs to, so a document with tel:name and crm:name side by side can't be told apart this way. If that matters, quick-xml's NsReader resolves each prefix to its URI and you handle the events yourself.

CDATA and escaped characters

Notes fields are where people stuff text that would otherwise need escaping. A CDATA section is the XML way of saying "take this literally", and quick-xml reads it into a normal String. Character references like &#246; are decoded for you too.

Rust
use quick_xml::de::from_str;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Subscriber {
    name: String,
    note: String,
}

fn main() -> Result<(), quick_xml::DeError> {
    let xml = r#"<subscriber>
  <name>Ingrid Hallstr&#246;m</name>
  <note><![CDATA[Ported from <Telia> on 2026-03-02 & verified]]></note>
</subscriber>"#;

    let sub: Subscriber = from_str(xml)?;
    println!("name: {}", sub.name);
    println!("note: {}", sub.note);
    Ok(())
}
name: Ingrid Hallström
note: Ported from <Telia> on 2026-03-02 & verified

When the XML doesn't match

The errors look much like serde_json's, just without the line and column:

Rust
use quick_xml::de::from_str;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Subscriber {
    name: String,
    roaming: bool,
}

fn main() {
    let bad_value = "<subscriber><name>Maeve</name><roaming>maybe</roaming></subscriber>";
    let missing = "<subscriber><name>Maeve</name></subscriber>";

    for xml in [bad_value, missing] {
        match from_str::<Subscriber>(xml) {
            Ok(s) => println!("parsed: {s:?}"),
            Err(e) => println!("error: {e}"),
        }
    }
}
error: invalid type: string "maybe", expected a boolean
error: missing field `roaming`

Because there is no position, a missing-field error on a big document can take a while to track down. If you suspect the file itself is broken rather than your struct, run it through the XML validator first. An unclosed tag gets reported there with a line number.

Big files: stream with Reader instead

from_str needs the whole document in memory. That's fine for an API response, and a problem for a 3 GB nightly export with a few million subscribers. For that, drop down to Reader, which hands you one event at a time. If opening and buffering files in Rust is new to you, this Rust tutorial on file I/O covers the basics. Our test file holds two records:

XML
<subscribers>
  <subscriber id="SUB-20417">
    <name>Ingrid Hallström</name>
    <iccid>8901240544102066246</iccid>
  </subscriber>
  <subscriber id="SUB-20418">
    <name>Maeve Lindqvist</name>
    <iccid>8901240544102066253</iccid>
  </subscriber>
</subscribers>
Rust
use quick_xml::events::Event;
use quick_xml::reader::Reader;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let mut reader = Reader::from_file("subscribers.xml")?;
    reader.config_mut().trim_text(true);

    let mut buf = Vec::new();
    let mut in_iccid = false;
    let mut count = 0;

    loop {
        match reader.read_event_into(&mut buf)? {
            Event::Start(e) if e.name().as_ref() == "subscriber" => count += 1,
            Event::Start(e) if e.name().as_ref() == "iccid" => in_iccid = true,
            Event::Text(t) if in_iccid => {
                let iccid: u64 = t.xml10_content().parse()?;
                println!("subscriber {count}: iccid {iccid}");
                in_iccid = false;
            }
            Event::Eof => break,
            _ => {}
        }
        buf.clear();
    }

    println!("{count} subscribers read");
    Ok(())
}
subscriber 1: iccid 8901240544102066246
subscriber 2: iccid 8901240544102066253
2 subscribers read

It is more code, and you have to keep track of where you are with flags like in_iccid. In exchange, memory use stays the same whether the file has two subscribers or two million. Don't skip buf.clear(): without it the buffer keeps every event you've read, and you are back to holding the file in memory.

Frequently Asked Questions

How do I parse XML in Rust?

Add quick-xml with the serialize feature plus serde with derive, describe the document as a struct with #[derive(Deserialize)], and call quick_xml::de::from_str. Child elements map to fields by name, attributes need an @ in front of the name, and an element's own text goes into a field renamed to $text. For very large files, use quick-xml's Reader and handle the events one at a time instead.

quick-xml vs serde-xml-rs — which should I use?

quick-xml is the one most projects pick today: it is fast, widely used, and gives you both serde deserialization and a low-level streaming Reader in the same crate. serde-xml-rs sits on top of the older xml-rs parser and uses different conventions for attributes and text. A struct written for one usually needs changes before it works with the other, so pick one early and stick with it.

How do I read XML attributes with serde?

Rename the field with an @ in front of the attribute name, for example #[serde(rename = "@id")] id: String. Without the @, quick-xml looks for a child element called id and reports missing field `id`. The value is text in the XML, but you can still declare the field as u64 or bool and serde will parse it.

How do I parse a large XML file in Rust without loading it all?

Use quick_xml::reader::Reader::from_file and loop over read_event_into, which hands you one start tag, text node or end tag at a time, so memory stays flat however big the file is. Call buf.clear() after each event so the buffer does not keep growing. The trade-off is that you track where you are yourself, for example with a flag that is set while you are inside an iccid element.

Can quick-xml read CDATA?

Yes. A CDATA section is read as ordinary text, so <note><![CDATA[Ported from <Telia> & verified]]></note> fills a String field with Ported from <Telia> & verified, angle brackets and ampersand included. You do not need any extra attribute for it.

Why does my Option field come back as Some("") instead of None?

Because the element is there, it is just empty. quick-xml gives None only when the element is missing entirely, while <email/> and <email></email> both become Some(""). If empty should mean none in your program, filter it after parsing with .filter(|s| !s.is_empty()).

The short list to keep next to your editor

Field name for a child element, @name for an attribute, $text for the text inside, a struct for every wrapper element, rename to the singular name for repeated elements, and Option plus default for things that may not be there. When the file is too large for that, switch to Reader.

If the same record also reaches you as JSON, the serde_json guide walks through it with the same fields, so you can keep one set of types for both.