ooxml-core 0.1.0

OOXML 公共基座:OPC 打包层 + DrawingML 公共类型系统,服务于 pptx-rs / xlsx-rs / docx-rs
Documentation
//! XML 转义工具。
//!
//! 提供 [`xml_escape`] 函数,用于 XML 属性值和文本内容的转义。
//!
//! 本模块是 OPC 层([`crate::opc`])和 OOXML 层([`crate::oxml`])的共享基础设施,
//! 避免各模块各自实现转义逻辑导致行为不一致。

/// XML 转义:将 `&` / `<` / `>` / `"` / `'` 转为对应的实体引用。
///
/// 用于 XML 属性值和文本内容的转义,避免 XML 注入和解析错误。
///
/// # 示例
///
/// ```
/// use ooxml_core::escape::xml_escape;
///
/// assert_eq!(xml_escape("a < b & c > d"), "a &lt; b &amp; c &gt; d");
/// assert_eq!(xml_escape(r#"say "hi""#), "say &quot;hi&quot;");
/// ```
pub fn xml_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            _ => out.push(c),
        }
    }
    out
}