Search code examples
xmlrustserde

Can rust and serde-xml-rs parse comments from XML files?


<foo>
  <!-- 2021-03-17 08:15:00 EST -->
  <row>
     <value>100</value>
  </row>
</foo>

I would like to get the comment from an XML file and was wondering if that was possible and if so how? I didn't see an example of that. In the above example, i would like to get "2021-03-17 08:15:00 EST"


Solution

  • No, at this time serde-xml-rs does not support parsing comments from XML files. See here in the source; they skip comments all together.

    But there's an open pull request to add support for parsing comments.

    So if you want to parse comments right now (with a disclaimer that this is not stable because you use somebody's github fork to do it) you could use the fork of the author of above pull request in this way:

    // Cargo.toml contains:
    //
    // [dependencies]
    // serde = {version = "1.0", features = ["derive"]}
    // serde-xml-rs = {git = "https://github.com/elmarco/serde-xml-rs.git", branch = "comment"}
    
    use serde::Deserialize;
    use serde_xml_rs::from_reader;
    
    #[derive(Debug, Deserialize)]
    pub struct Foo {
        #[serde(rename = "$comment")]
        pub date: Option<String>,
        pub row: RowValue,
    }
    
    #[derive(Debug, Deserialize)]
    pub struct RowValue {
        pub value: i32,
    }
    
    fn main() {
        let input = "<foo> \
                       <!-- 2021-03-17 08:15:00 EST --> \
                       <row> \
                          <value>100</value> \
                       </row> \
                     </foo>";
    
        let foo: Foo = from_reader(input.as_bytes()).unwrap();
        println!("input={:#?}", foo);
    }