Skip to main content

nenjo_xml/xml/
parse.rs

1//! Simple XML parsing utilities for extracting content and attributes.
2//!
3//! These functions operate on XML strings and provide basic extraction
4//! capabilities without requiring a full XML parser. They are designed for
5//! the structured XML used in LLM prompts, which tends to be well-formed
6//! and predictable.
7//!
8//! For complex XML parsing needs, consider using a full parser like `quick-xml`.
9
10use super::xml_unescape;
11
12/// Error type for XML parsing operations.
13#[derive(Debug, thiserror::Error)]
14pub enum XmlError {
15    #[error("tag not found: <{0}>")]
16    TagNotFound(String),
17    #[error("attribute '{attr}' not found on <{tag}>")]
18    AttrNotFound { tag: String, attr: String },
19    #[error("parse error: {0}")]
20    Parse(String),
21}
22
23pub type Result<T> = std::result::Result<T, XmlError>;
24
25/// Extracts the text content of the first occurrence of a tag.
26///
27/// Returns the unescaped text between `<name>` and `</name>`.
28///
29/// # Examples
30///
31/// ```
32/// use nenjo_xml::xml::parse::extract_tag_content;
33///
34/// let xml = "<task><title>Fix bug</title><priority>high</priority></task>";
35/// assert_eq!(extract_tag_content(xml, "title").unwrap(), "Fix bug");
36/// assert_eq!(extract_tag_content(xml, "priority").unwrap(), "high");
37/// ```
38///
39/// Handles XML entities:
40///
41/// ```
42/// use nenjo_xml::xml::parse::extract_tag_content;
43///
44/// let xml = "<msg>a &lt; b &amp; c</msg>";
45/// assert_eq!(extract_tag_content(xml, "msg").unwrap(), "a < b & c");
46/// ```
47pub fn extract_tag_content(xml: &str, tag_name: &str) -> Result<String> {
48    let open_tag_prefix = format!("<{}", tag_name);
49    let close_tag = format!("</{}>", tag_name);
50
51    // Find the opening tag (which may have attributes)
52    let open_start = xml
53        .find(&open_tag_prefix)
54        .ok_or_else(|| XmlError::TagNotFound(tag_name.to_string()))?;
55
56    // Find the end of the opening tag (the '>' character)
57    let content_start = xml[open_start..]
58        .find('>')
59        .ok_or_else(|| XmlError::Parse(format!("malformed opening tag <{}>", tag_name)))?
60        + open_start
61        + 1;
62
63    // Check for self-closing tag
64    if xml[open_start..content_start].ends_with("/>") {
65        return Ok(String::new());
66    }
67
68    // Find the closing tag
69    let content_end = xml[content_start..]
70        .find(&close_tag)
71        .ok_or_else(|| XmlError::TagNotFound(tag_name.to_string()))?
72        + content_start;
73
74    let raw_content = &xml[content_start..content_end];
75    Ok(xml_unescape(raw_content))
76}
77
78/// Extracts all occurrences of a tag's text content.
79///
80/// Returns a vector of unescaped strings, one per occurrence.
81///
82/// # Examples
83///
84/// ```
85/// use nenjo_xml::xml::parse::extract_all_tag_contents;
86///
87/// let xml = "<list><item>A</item><item>B</item><item>C</item></list>";
88/// let items = extract_all_tag_contents(xml, "item").unwrap();
89/// assert_eq!(items, vec!["A", "B", "C"]);
90/// ```
91pub fn extract_all_tag_contents(xml: &str, tag_name: &str) -> Result<Vec<String>> {
92    let mut results = Vec::new();
93    let open_tag_prefix = format!("<{}", tag_name);
94    let close_tag = format!("</{}>", tag_name);
95    let mut search_from = 0;
96
97    while let Some(pos) = xml[search_from..].find(&open_tag_prefix) {
98        let open_start = search_from + pos;
99
100        // Ensure it's actually a tag boundary (next char is whitespace, '>', or '/')
101        let after_prefix = open_start + open_tag_prefix.len();
102        if after_prefix < xml.len() {
103            let next_char = xml.as_bytes()[after_prefix];
104            if next_char != b'>'
105                && next_char != b' '
106                && next_char != b'/'
107                && next_char != b'\t'
108                && next_char != b'\n'
109            {
110                search_from = after_prefix;
111                continue;
112            }
113        }
114
115        // Find end of opening tag
116        let content_start = match xml[open_start..].find('>') {
117            Some(pos) => open_start + pos + 1,
118            None => break,
119        };
120
121        // Self-closing tag
122        if xml[open_start..content_start].ends_with("/>") {
123            results.push(String::new());
124            search_from = content_start;
125            continue;
126        }
127
128        // Find closing tag
129        let content_end = match xml[content_start..].find(&close_tag) {
130            Some(pos) => content_start + pos,
131            None => break,
132        };
133
134        results.push(xml_unescape(&xml[content_start..content_end]));
135        search_from = content_end + close_tag.len();
136    }
137
138    if results.is_empty() {
139        return Err(XmlError::TagNotFound(tag_name.to_string()));
140    }
141
142    Ok(results)
143}
144
145/// Extracts the value of an attribute from the first occurrence of a tag.
146///
147/// Returns the unescaped attribute value.
148///
149/// # Examples
150///
151/// ```
152/// use nenjo_xml::xml::parse::extract_attr;
153///
154/// let xml = r#"<task id="42" status="open">Fix bug</task>"#;
155/// assert_eq!(extract_attr(xml, "task", "id").unwrap(), "42");
156/// assert_eq!(extract_attr(xml, "task", "status").unwrap(), "open");
157/// ```
158pub fn extract_attr(xml: &str, tag_name: &str, attr_name: &str) -> Result<String> {
159    let open_tag_prefix = format!("<{}", tag_name);
160
161    let open_start = xml
162        .find(&open_tag_prefix)
163        .ok_or_else(|| XmlError::TagNotFound(tag_name.to_string()))?;
164
165    // Find the end of the opening tag
166    let tag_end = xml[open_start..]
167        .find('>')
168        .ok_or_else(|| XmlError::Parse(format!("malformed opening tag <{}>", tag_name)))?
169        + open_start;
170
171    let tag_str = &xml[open_start..=tag_end];
172
173    // Look for the attribute
174    let attr_pattern = format!("{}=\"", attr_name);
175    let attr_start = tag_str
176        .find(&attr_pattern)
177        .ok_or_else(|| XmlError::AttrNotFound {
178            tag: tag_name.to_string(),
179            attr: attr_name.to_string(),
180        })?;
181
182    let value_start = attr_start + attr_pattern.len();
183    let value_end = tag_str[value_start..]
184        .find('"')
185        .ok_or_else(|| XmlError::Parse(format!("unclosed attribute value for '{}'", attr_name)))?
186        + value_start;
187
188    let raw_value = &tag_str[value_start..value_end];
189    Ok(xml_unescape(raw_value))
190}
191
192/// Checks if a specific tag exists in the XML string.
193///
194/// # Examples
195///
196/// ```
197/// use nenjo_xml::xml::parse::has_tag;
198///
199/// let xml = "<root><name>Alice</name></root>";
200/// assert!(has_tag(xml, "name"));
201/// assert!(!has_tag(xml, "age"));
202/// ```
203pub fn has_tag(xml: &str, tag_name: &str) -> bool {
204    let open_tag_prefix = format!("<{}", tag_name);
205    if let Some(pos) = xml.find(&open_tag_prefix) {
206        let after = pos + open_tag_prefix.len();
207        if after < xml.len() {
208            let ch = xml.as_bytes()[after];
209            return ch == b'>' || ch == b' ' || ch == b'/' || ch == b'\t' || ch == b'\n';
210        }
211    }
212    false
213}
214
215/// Extracts the raw (unprocessed) inner XML of a tag, including nested tags.
216///
217/// Unlike [`extract_tag_content`], this does NOT unescape entities. Useful
218/// when the inner content is itself XML that you want to process further.
219///
220/// # Examples
221///
222/// ```
223/// use nenjo_xml::xml::parse::extract_raw_inner_xml;
224///
225/// let xml = "<root><child>text</child></root>";
226/// assert_eq!(extract_raw_inner_xml(xml, "root").unwrap(), "<child>text</child>");
227/// ```
228pub fn extract_raw_inner_xml(xml: &str, tag_name: &str) -> Result<String> {
229    let open_tag_prefix = format!("<{}", tag_name);
230    let close_tag = format!("</{}>", tag_name);
231
232    let open_start = xml
233        .find(&open_tag_prefix)
234        .ok_or_else(|| XmlError::TagNotFound(tag_name.to_string()))?;
235
236    let content_start = xml[open_start..]
237        .find('>')
238        .ok_or_else(|| XmlError::Parse(format!("malformed opening tag <{}>", tag_name)))?
239        + open_start
240        + 1;
241
242    if xml[open_start..content_start].ends_with("/>") {
243        return Ok(String::new());
244    }
245
246    // For nested same-name tags, we need to find the matching close tag
247    let mut depth = 1;
248    let mut search_pos = content_start;
249
250    while depth > 0 {
251        // Find next open or close of same tag name
252        let next_open = xml[search_pos..].find(&open_tag_prefix);
253        let next_close = xml[search_pos..].find(&close_tag);
254
255        match (next_open, next_close) {
256            (_, None) => {
257                return Err(XmlError::Parse(format!(
258                    "missing closing tag </{}>",
259                    tag_name
260                )));
261            }
262            (Some(o), Some(c)) if o < c => {
263                // Check it's actually a tag boundary
264                let after = search_pos + o + open_tag_prefix.len();
265                if after < xml.len() {
266                    let ch = xml.as_bytes()[after];
267                    if ch == b'>' || ch == b' ' || ch == b'/' || ch == b'\t' || ch == b'\n' {
268                        depth += 1;
269                    }
270                }
271                search_pos += o + 1;
272            }
273            (_, Some(c)) => {
274                depth -= 1;
275                if depth == 0 {
276                    let content_end = search_pos + c;
277                    return Ok(xml[content_start..content_end].to_string());
278                }
279                search_pos += c + close_tag.len();
280            }
281        }
282    }
283
284    Err(XmlError::Parse(format!(
285        "unexpected end parsing <{}>",
286        tag_name
287    )))
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    // ---- extract_tag_content ----
295
296    #[test]
297    fn test_extract_simple() {
298        let xml = "<name>Alice</name>";
299        assert_eq!(extract_tag_content(xml, "name").unwrap(), "Alice");
300    }
301
302    #[test]
303    fn test_extract_with_surrounding() {
304        let xml = "<root><name>Bob</name><age>30</age></root>";
305        assert_eq!(extract_tag_content(xml, "name").unwrap(), "Bob");
306        assert_eq!(extract_tag_content(xml, "age").unwrap(), "30");
307    }
308
309    #[test]
310    fn test_extract_with_attrs() {
311        let xml = r#"<task id="1">content</task>"#;
312        assert_eq!(extract_tag_content(xml, "task").unwrap(), "content");
313    }
314
315    #[test]
316    fn test_extract_with_entities() {
317        let xml = "<msg>a &lt; b &amp; c &gt; d</msg>";
318        assert_eq!(extract_tag_content(xml, "msg").unwrap(), "a < b & c > d");
319    }
320
321    #[test]
322    fn test_extract_nested_xml_content() {
323        let xml = "<root><inner>text</inner></root>";
324        // This extracts everything between <root> and </root>, including inner tags
325        let content = extract_tag_content(xml, "root").unwrap();
326        assert_eq!(content, "<inner>text</inner>");
327    }
328
329    #[test]
330    fn test_extract_self_closing() {
331        let xml = "<item />";
332        assert_eq!(extract_tag_content(xml, "item").unwrap(), "");
333    }
334
335    #[test]
336    fn test_extract_not_found() {
337        let xml = "<name>Alice</name>";
338        assert!(extract_tag_content(xml, "age").is_err());
339    }
340
341    #[test]
342    fn test_extract_empty_content() {
343        let xml = "<name></name>";
344        assert_eq!(extract_tag_content(xml, "name").unwrap(), "");
345    }
346
347    // ---- extract_all_tag_contents ----
348
349    #[test]
350    fn test_extract_all() {
351        let xml = "<list><item>A</item><item>B</item><item>C</item></list>";
352        let items = extract_all_tag_contents(xml, "item").unwrap();
353        assert_eq!(items, vec!["A", "B", "C"]);
354    }
355
356    #[test]
357    fn test_extract_all_single() {
358        let xml = "<list><item>A</item></list>";
359        let items = extract_all_tag_contents(xml, "item").unwrap();
360        assert_eq!(items, vec!["A"]);
361    }
362
363    #[test]
364    fn test_extract_all_not_found() {
365        let xml = "<list></list>";
366        assert!(extract_all_tag_contents(xml, "item").is_err());
367    }
368
369    #[test]
370    fn test_extract_all_with_entities() {
371        let xml = "<list><v>a &amp; b</v><v>c &lt; d</v></list>";
372        let vals = extract_all_tag_contents(xml, "v").unwrap();
373        assert_eq!(vals, vec!["a & b", "c < d"]);
374    }
375
376    #[test]
377    fn test_extract_all_no_false_prefix_match() {
378        let xml = "<items><item>A</item><item_extra>B</item_extra></items>";
379        let items = extract_all_tag_contents(xml, "item").unwrap();
380        assert_eq!(items, vec!["A"]);
381    }
382
383    // ---- extract_attr ----
384
385    #[test]
386    fn test_extract_attr_simple() {
387        let xml = r#"<task id="42">content</task>"#;
388        assert_eq!(extract_attr(xml, "task", "id").unwrap(), "42");
389    }
390
391    #[test]
392    fn test_extract_attr_multiple() {
393        let xml = r#"<task id="42" status="open" priority="high">c</task>"#;
394        assert_eq!(extract_attr(xml, "task", "id").unwrap(), "42");
395        assert_eq!(extract_attr(xml, "task", "status").unwrap(), "open");
396        assert_eq!(extract_attr(xml, "task", "priority").unwrap(), "high");
397    }
398
399    #[test]
400    fn test_extract_attr_with_entities() {
401        let xml = r#"<item label="a &amp; b">c</item>"#;
402        assert_eq!(extract_attr(xml, "item", "label").unwrap(), "a & b");
403    }
404
405    #[test]
406    fn test_extract_attr_tag_not_found() {
407        let xml = "<name>Alice</name>";
408        assert!(extract_attr(xml, "task", "id").is_err());
409    }
410
411    #[test]
412    fn test_extract_attr_attr_not_found() {
413        let xml = r#"<task id="42">c</task>"#;
414        assert!(extract_attr(xml, "task", "status").is_err());
415    }
416
417    #[test]
418    fn test_extract_attr_self_closing() {
419        let xml = r#"<br class="clear" />"#;
420        assert_eq!(extract_attr(xml, "br", "class").unwrap(), "clear");
421    }
422
423    // ---- has_tag ----
424
425    #[test]
426    fn test_has_tag_true() {
427        assert!(has_tag("<root><name>A</name></root>", "name"));
428    }
429
430    #[test]
431    fn test_has_tag_false() {
432        assert!(!has_tag("<root><name>A</name></root>", "age"));
433    }
434
435    #[test]
436    fn test_has_tag_no_prefix_match() {
437        assert!(!has_tag(
438            "<items><item_extra>A</item_extra></items>",
439            "item"
440        ));
441    }
442
443    #[test]
444    fn test_has_tag_self_closing() {
445        assert!(has_tag("<root><br /></root>", "br"));
446    }
447
448    // ---- extract_raw_inner_xml ----
449
450    #[test]
451    fn test_raw_inner_simple() {
452        let xml = "<root><child>text</child></root>";
453        assert_eq!(
454            extract_raw_inner_xml(xml, "root").unwrap(),
455            "<child>text</child>"
456        );
457    }
458
459    #[test]
460    fn test_raw_inner_nested_same_name() {
461        let xml = "<div><div>inner</div></div>";
462        assert_eq!(
463            extract_raw_inner_xml(xml, "div").unwrap(),
464            "<div>inner</div>"
465        );
466    }
467
468    #[test]
469    fn test_raw_inner_preserves_entities() {
470        let xml = "<root>a &lt; b</root>";
471        assert_eq!(extract_raw_inner_xml(xml, "root").unwrap(), "a &lt; b");
472    }
473
474    #[test]
475    fn test_raw_inner_self_closing() {
476        let xml = "<root />";
477        assert_eq!(extract_raw_inner_xml(xml, "root").unwrap(), "");
478    }
479}