Skip to content

Serialize to String works, but Deserialize from that same String fails on version 0.27.1 #537

Closed
@ZakisM

Description

@ZakisM

Consider this code:

use serde::{Deserialize, Serialize};

use crate::Result;

#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SiteMap {
    #[serde(rename = "urlset")]
    url_set: Urlset,
}

impl SiteMap {
    pub fn new() -> Self {
        Self {
            url_set: Urlset {
                xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9".to_string(),
                xmlns_image: "http://www.google.com/schemas/sitemap-image/1.1".to_string(),
            },
        }
    }

    pub fn to_xml_string(&self) -> Result<String> {
        let mut xml = String::from("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        let xml_body = quick_xml::se::to_string(&self)?;

        xml.push_str(&xml_body);

        Ok(xml)
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename = "urlset", rename_all = "lowercase")]
pub struct Urlset {
    #[serde(rename = "@xmlns")]
    xmlns: String,
    #[serde(rename = "@xmlns:image")]
    xmlns_image: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    const SITEMAP_RAW: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\"/>";

    #[test]
    fn test_write_sitemap() {
        let sitemap = SiteMap::new();
        let sitemap_r = sitemap.to_xml_string().expect("Failed to write sitemap");

        assert_eq!(&sitemap_r, SITEMAP_RAW);
    }

    #[test]
    fn test_read_sitemap() {
        let sitemap: SiteMap =
            quick_xml::de::from_str(SITEMAP_RAW).expect("Failed to read sitemap");
    }
}

The test_read_sitemap test fails. Seems to be because of the colon in xmlns:image. If I change the rename for image to:

#[serde(rename = "@image")]
xmlns_image: String,

and then change the SITEMAP_RAW string to:

const SITEMAP_RAW: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" image=\"http://www.google.com/schemas/sitemap-image/1.1\"/>";

Then the test passes. This was working fine in version 0.26 but is failing in 0.27.1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    namespacesIssues related to namespaces supportserdeIssues related to mapping from Rust types to XML

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions