首页 > 解决方案 > rust 和 serde-xml-rs 可以解析 XML 文件中的注释吗?

问题描述

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

我想从 XML 文件中获取评论,想知道这是否可能,如果可能,如何?我没有看到这样的例子。在上面的例子中,我想得到“2021-03-17 08:15:00 EST”

标签: xmlrustserde

解决方案


不,目前 serde-xml-rs 不支持解析 XML 文件中的注释。请参阅源代码中的此处;他们一起跳过评论。

但是有一个开放的拉取请求来添加对解析评论的支持。

因此,如果您现在想解析评论(并声明这是不稳定的,因为您使用某人的 github 分支来执行此操作),您可以通过这种方式使用上述拉取请求作者的分支:

// 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);
}

推荐阅读