gpt4 book ai didi

rust - 将 http 响应解析为 (chrono::DateTime, f32) 的元组向量

转载 作者:行者123 更新时间:2023-12-05 05:37:07 26 4
gpt4 key购买 nike

我向服务器发送 http get 请求并收到响应:

let resp = reqwest::blocking::get(req)?.text()?;

resp 持有一个 String,如下所示:

<?xml version=\"1.0\" encoding=\"UTF-8\">\n<Document xmlns=...
<datetime>202207102300</datetime>\n\t\t\t\t\t\t<value>320.08</value>\n\t\t\t\t\t<datetime>202207110000</datetime>\n\t\t\t\t\t\t<value>278.00</value>
...</Document>

将此文本解析为包含元组元素的向量的最佳方法是什么,如下所示:

let mut tuple_items: (chrono::DateTime, f32)

最佳答案

这是我用 quickxml crate 创建的代码:

use chrono::NaiveDateTime;
use quick_xml::events::Event;
use quick_xml::Reader;

pub struct DatetimeValue {
pub dt: NaiveDateTime,
pub val: f32,
}

pub fn parse_xml_string(&self, xml_string: String) -> Vec<DatetimeValue> {
let mut response_vector: Vec<DatetimeValue> = vec![];
let mut reader = Reader::from_str(&xml_string[..]);
reader.trim_text(true);
let mut val_flag = false;
let mut dt_flag = false;
let mut buf = Vec::new();
let mut count = 0;
let mut actual_dt: NaiveDateTime;
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => {
if let b"value" = e.name() { val_flag = true }
else if let b"datetime" = e.name() { dt_flag = true }
}
Ok(Event::Text(e)) => {
if dt_flag {
actual_dt = NaiveDateTime::parse_from_str(e
.unescape_and_decode(&reader)
.unwrap(), "%Y%m%d%H%M").unwrap();
dt_flag = false;
}
else if val_flag {
response_vector.push(DatetimeValue {
dt: actual_dt,
val: e
.unescape_and_decode(&reader)
.unwrap()
.parse::<f32>()
.unwrap(),
});
val_flag = false;
}
}
Ok(Event::Eof) => break,
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
response_vector
}

关于rust - 将 http 响应解析为 (chrono::DateTime, f32) 的元组向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73186261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com