docx_rs/documents/
custom_item.rs

1use crate::documents::BuildXML;
2use crate::xml_builder::XMLBuilder;
3use crate::{ParseXmlError, XmlDocument};
4use serde::ser::SerializeSeq;
5use serde::Serialize;
6use std::io::Write;
7use std::str::FromStr;
8
9#[derive(Debug, Clone)]
10pub struct CustomItem(XmlDocument);
11
12impl FromStr for CustomItem {
13    type Err = ParseXmlError;
14
15    fn from_str(s: &str) -> Result<Self, Self::Err> {
16        Ok(CustomItem(XmlDocument::from_str(s)?))
17    }
18}
19
20impl Serialize for CustomItem {
21    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
22    where
23        S: serde::Serializer,
24    {
25        let mut seq = serializer.serialize_seq(Some(self.0.data.len()))?;
26        for e in self.0.data.iter() {
27            seq.serialize_element(e)?;
28        }
29        seq.end()
30    }
31}
32
33impl BuildXML for CustomItem {
34    fn build_to<W: Write>(
35        &self,
36        stream: xml::writer::EventWriter<W>,
37    ) -> xml::writer::Result<xml::writer::EventWriter<W>> {
38        let mut b = XMLBuilder::from(stream);
39        write!(b.inner_mut()?, "{}", self.0)?;
40        b.into_inner()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46
47    use super::*;
48    #[cfg(test)]
49    use pretty_assertions::assert_eq;
50
51    #[test]
52    fn test_custom_xml() {
53        let c = CustomItem::from_str(
54            r#"<ds:datastoreItem ds:itemID="{06AC5857-5C65-A94A-BCEC-37356A209BC3}" xmlns:ds="http://schemas.openxmlformats.org/officeDocument/2006/customXml"><ds:schemaRefs><ds:schemaRef ds:uri="https://hoge.com"></ds:schemaRef></ds:schemaRefs></ds:datastoreItem>"#,
55        )
56        .unwrap();
57
58        assert_eq!(
59            c.0.to_string(),
60            r#"<ds:datastoreItem ds:itemID="{06AC5857-5C65-A94A-BCEC-37356A209BC3}" xmlns:ds="http://schemas.openxmlformats.org/officeDocument/2006/customXml"><ds:schemaRefs><ds:schemaRef ds:uri="https://hoge.com"></ds:schemaRef></ds:schemaRefs></ds:datastoreItem>"#
61        );
62        assert_eq!(
63            serde_json::to_string(&c).unwrap(),
64        "[{\"name\":\"ds:datastoreItem\",\"attributes\":[[\"ds:itemID\",\"{06AC5857-5C65-A94A-BCEC-37356A209BC3}\"],[\"xmlns:ds\",\"http://schemas.openxmlformats.org/officeDocument/2006/customXml\"]],\"data\":null,\"children\":[{\"name\":\"ds:schemaRefs\",\"attributes\":[],\"data\":null,\"children\":[{\"name\":\"ds:schemaRef\",\"attributes\":[[\"ds:uri\",\"https://hoge.com\"]],\"data\":null,\"children\":[]}]}]}]"
65        );
66    }
67}