office-rs 0.1.1

A Rust library for reading and writing XML Office files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! XML处理工具模块
//! 提供Office文档XML解析和生成的通用功能

use crate::context::ErrorContext;
use crate::error::{ OfficeError, Result };
use quick_xml::events::{ BytesEnd, BytesStart, BytesText, Event };
use quick_xml::{ Reader, Writer };
use std::collections::HashMap;
use std::io::{ BufRead, Write };

/// XML命名空间管理器
#[derive(Debug, Clone)]
pub struct NamespaceManager {
    namespaces: HashMap<String, String>,
    default_namespace: Option<String>,
}

impl NamespaceManager {
    /// 创建新的命名空间管理器
    pub fn new() -> Self {
        Self {
            namespaces: HashMap::new(),
            default_namespace: None,
        }
    }

    /// 添加命名空间映射
    pub fn add_namespace(&mut self, prefix: String, uri: String) {
        self.namespaces.insert(prefix, uri);
    }

    /// 设置默认命名空间
    pub fn set_default_namespace(&mut self, uri: String) {
        self.default_namespace = Some(uri);
    }

    /// 获取命名空间URI
    pub fn get_namespace_uri(&self, prefix: &str) -> Option<&String> {
        self.namespaces.get(prefix)
    }

    /// 解析带命名空间的元素名
    pub fn parse_qualified_name<'a>(&self, name: &'a str) -> (Option<&String>, &'a str) {
        if let Some(colon_pos) = name.find(':') {
            let prefix = &name[..colon_pos];
            let local_name = &name[colon_pos + 1..];
            (self.get_namespace_uri(prefix), local_name)
        } else {
            (self.default_namespace.as_ref(), name)
        }
    }
}

/// XML元素信息
#[derive(Debug, Clone)]
pub struct XmlElement {
    pub name: String,
    pub attributes: HashMap<String, String>,
    pub text_content: Option<String>,
    pub children: Vec<XmlElement>,
}

impl XmlElement {
    /// 创建新的XML元素
    pub fn new<S: AsRef<str>>(name: S) -> Self {
        Self {
            name: name.as_ref().to_string(),
            attributes: HashMap::new(),
            text_content: None,
            children: Vec::new(),
        }
    }

    /// 添加属性
    pub fn add_attribute<K: AsRef<str>, V: AsRef<str>>(&mut self, name: K, value: V) {
        self.attributes.insert(name.as_ref().to_string(), value.as_ref().to_string());
    }

    /// 获取属性值
    pub fn get_attribute(&self, name: &str) -> Option<&String> {
        self.attributes.get(name)
    }

    /// 设置文本内容
    pub fn set_text_content<S: AsRef<str>>(&mut self, content: S) {
        self.text_content = Some(content.as_ref().to_string());
    }

    /// 添加子元素
    pub fn add_child(&mut self, child: XmlElement) {
        self.children.push(child);
    }

    /// 查找第一个匹配名称的子元素
    pub fn find_child(&self, name: &str) -> Option<&XmlElement> {
        self.children.iter().find(|child| child.name == name)
    }

    /// 查找所有匹配名称的子元素
    pub fn find_children(&self, name: &str) -> Vec<&XmlElement> {
        self.children
            .iter()
            .filter(|child| child.name == name)
            .collect()
    }

    /// 递归查找元素(深度优先搜索)
    pub fn find_element_recursive(&self, name: &str) -> Option<&XmlElement> {
        if self.name == name {
            return Some(self);
        }

        for child in &self.children {
            if let Some(found) = child.find_element_recursive(name) {
                return Some(found);
            }
        }

        None
    }
}

/// XML解析器
pub struct XmlParser {
    namespace_manager: NamespaceManager,
}

impl XmlParser {
    /// 创建新的XML解析器
    pub fn new() -> Self {
        Self {
            namespace_manager: NamespaceManager::new(),
        }
    }

    /// 添加命名空间
    pub fn add_namespace(&mut self, prefix: String, uri: String) {
        self.namespace_manager.add_namespace(prefix, uri);
    }

    /// 解析XML字符串为元素树
    pub fn parse_string(&self, xml_content: &str) -> Result<XmlElement> {
        let mut reader = Reader::from_str(xml_content);
        reader.config_mut().trim_text(true);

        let context = ErrorContext {
            operation: Some("解析XML字符串".to_string()),
            ..Default::default()
        };

        self.parse_element(&mut reader, &context)
    }

    /// 解析XML字节流为元素树
    pub fn parse_bytes(&self, xml_bytes: &[u8]) -> Result<XmlElement> {
        let mut reader = Reader::from_reader(xml_bytes);
        reader.config_mut().trim_text(true);

        let context = ErrorContext {
            operation: Some("解析XML字节流".to_string()),
            ..Default::default()
        };

        self.parse_element(&mut reader, &context)
    }

    /// 内部解析方法
    fn parse_element<R: BufRead>(
        &self,
        reader: &mut Reader<R>,
        context: &ErrorContext
    ) -> Result<XmlElement> {
        let mut buf = Vec::new();
        let mut element_stack: Vec<XmlElement> = Vec::new();
        let mut root_element: Option<XmlElement> = None;

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref e)) => {
                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
                    let mut element = XmlElement::new(name);

                    // 解析属性
                    for attr in e.attributes() {
                        let attr = attr.map_err(|e| {
                            OfficeError::Xml(quick_xml::Error::InvalidAttr(e)).with_context(
                                context.clone()
                            )
                        })?;
                        let key = String::from_utf8_lossy(attr.key.as_ref()).to_string();
                        let value = String::from_utf8_lossy(&attr.value).to_string();
                        element.add_attribute(key, value);
                    }

                    element_stack.push(element);
                }
                Ok(Event::End(_)) => {
                    if let Some(element) = element_stack.pop() {
                        if let Some(parent) = element_stack.last_mut() {
                            parent.add_child(element);
                        } else {
                            root_element = Some(element);
                            break;
                        }
                    }
                }
                Ok(Event::Text(ref e)) => {
                    let text = std::str::from_utf8(e.as_ref()).unwrap_or("");
                    if let Some(element) = element_stack.last_mut() {
                        element.set_text_content(text.to_string());
                    }
                }
                Ok(Event::Empty(ref e)) => {
                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
                    let mut element = XmlElement::new(name);

                    // 解析属性
                    for attr in e.attributes() {
                        let attr = attr.map_err(|e| {
                            OfficeError::Xml(quick_xml::Error::InvalidAttr(e)).with_context(
                                context.clone()
                            )
                        })?;
                        let key = String::from_utf8_lossy(attr.key.as_ref()).to_string();
                        let value = String::from_utf8_lossy(&attr.value).to_string();
                        element.add_attribute(key, value);
                    }

                    if let Some(parent) = element_stack.last_mut() {
                        parent.add_child(element);
                    } else {
                        root_element = Some(element);
                        break;
                    }
                }
                Ok(Event::Eof) => {
                    break;
                }
                Err(e) => {
                    return Err(OfficeError::Xml(e).with_context(context.clone()));
                }
                _ => {} // 忽略其他事件
            }
            buf.clear();
        }

        root_element.ok_or_else(|| {
            OfficeError::parse_error_with_context("root".to_string(), context.clone())
        })
    }
}

/// XML生成器
pub struct XmlGenerator {
    namespace_manager: NamespaceManager,
}

impl XmlGenerator {
    /// 创建新的XML生成器
    pub fn new() -> Self {
        Self {
            namespace_manager: NamespaceManager::new(),
        }
    }

    /// 添加命名空间
    pub fn add_namespace(&mut self, prefix: String, uri: String) {
        self.namespace_manager.add_namespace(prefix, uri);
    }

    /// 将元素树生成为XML字符串
    pub fn generate_string(&self, element: &XmlElement) -> Result<String> {
        let mut output = Vec::new();
        {
            let mut writer = Writer::new(&mut output);
            self.write_element(&mut writer, element)?;
        }

        String::from_utf8(output).map_err(|e| OfficeError::Other(format!("UTF-8编码错误: {}", e)))
    }

    /// 将元素树写入Writer
    pub fn write_element<W: Write>(
        &self,
        writer: &mut Writer<W>,
        element: &XmlElement
    ) -> Result<()> {
        let context = ErrorContext {
            operation: Some("生成XML".to_string()),
            ..Default::default()
        };

        // 创建开始标签
        let mut start_tag = BytesStart::new(&element.name);

        // 添加属性
        for (key, value) in &element.attributes {
            start_tag.push_attribute((key.as_str(), value.as_str()));
        }

        if element.children.is_empty() && element.text_content.is_none() {
            // 空元素
            writer
                .write_event(Event::Empty(start_tag))
                .map_err(|e| OfficeError::Xml(e.into()).with_context(context.clone()))?;
        } else {
            // 有内容的元素
            writer
                .write_event(Event::Start(start_tag))
                .map_err(|e| OfficeError::Xml(e.into()).with_context(context.clone()))?;

            // 写入文本内容
            if let Some(text) = &element.text_content {
                writer
                    .write_event(Event::Text(BytesText::new(text)))
                    .map_err(|e| OfficeError::Xml(e.into()).with_context(context.clone()))?;
            }

            // 递归写入子元素
            for child in &element.children {
                self.write_element(writer, child)?;
            }

            // 写入结束标签
            writer
                .write_event(Event::End(BytesEnd::new(&element.name)))
                .map_err(|e| OfficeError::Xml(e.into()).with_context(context.clone()))?;
        }

        Ok(())
    }
}

/// XML工具函数
pub mod utils {
    use super::*;

    /// 转义XML特殊字符
    pub fn escape_xml(text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
            .replace('\'', "&apos;")
    }

    /// 反转义XML特殊字符
    pub fn unescape_xml(text: &str) -> String {
        text.replace("&amp;", "&")
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&quot;", "\"")
            .replace("&apos;", "'")
    }

    /// 验证XML元素名称
    pub fn is_valid_xml_name(name: &str) -> bool {
        if name.is_empty() {
            return false;
        }

        let first_char = name.chars().next().unwrap();
        if !first_char.is_alphabetic() && first_char != '_' {
            return false;
        }

        name.chars().all(|c| (c.is_alphanumeric() || c == '_' || c == '-' || c == '.'))
    }

    /// 格式化XML(添加缩进)
    pub fn format_xml(xml: &str, indent: &str) -> Result<String> {
        let parser = XmlParser::new();
        let element = parser.parse_string(xml)?;

        let mut result = String::new();
        format_element(&element, &mut result, indent, 0);
        Ok(result)
    }

    fn format_element(element: &XmlElement, result: &mut String, indent: &str, level: usize) {
        let current_indent = indent.repeat(level);

        // 开始标签
        result.push_str(&current_indent);
        result.push('<');
        result.push_str(&element.name);

        // 属性
        for (key, value) in &element.attributes {
            result.push_str(&format!(" {}=\"{}\"", key, escape_xml(value)));
        }

        if element.children.is_empty() && element.text_content.is_none() {
            result.push_str("/>\n");
        } else {
            result.push_str(">\n");

            // 文本内容
            if let Some(text) = &element.text_content {
                result.push_str(&indent.repeat(level + 1));
                result.push_str(&escape_xml(text));
                result.push('\n');
            }

            // 子元素
            for child in &element.children {
                format_element(child, result, indent, level + 1);
            }

            // 结束标签
            result.push_str(&current_indent);
            result.push_str(&format!("</{}>", element.name));
            result.push('\n');
        }
    }
}

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

    #[test]
    fn test_namespace_manager() {
        let mut ns_mgr = NamespaceManager::new();
        ns_mgr.add_namespace(
            "w".to_string(),
            "http://schemas.openxmlformats.org/wordprocessingml/2006/main".to_string()
        );

        let (ns_uri, local_name) = ns_mgr.parse_qualified_name("w:document");
        assert_eq!(local_name, "document");
        assert!(ns_uri.is_some());
    }

    #[test]
    fn test_xml_parsing() {
        let xml = r#"<root attr="value"><child>text</child></root>"#;
        let parser = XmlParser::new();
        let element = parser.parse_string(xml).unwrap();

        assert_eq!(element.name, "root");
        assert_eq!(element.get_attribute("attr"), Some(&"value".to_string()));
        assert_eq!(element.children.len(), 1);
        assert_eq!(element.children[0].name, "child");
        assert_eq!(element.children[0].text_content, Some("text".to_string()));
    }

    #[test]
    fn test_xml_generation() {
        let mut element = XmlElement::new("root");
        element.add_attribute("attr", "value");

        let mut child = XmlElement::new("child");
        child.set_text_content("text");
        element.add_child(child);

        let generator = XmlGenerator::new();
        let xml = generator.generate_string(&element).unwrap();

        assert!(xml.contains("<root attr=\"value\">"));
        assert!(xml.contains("<child>text</child>"));
        assert!(xml.contains("</root>"));
    }
}