use-xml 0.1.0

Lightweight XML declaration, element, and attribute helpers for RustUse
Documentation
use use_xml::{
    escape_xml, extract_attributes, extract_root_element, extract_xml_declaration, get_attribute,
    has_attribute, has_xml_declaration, looks_like_xml, strip_xml_comments, strip_xml_declaration,
    unescape_xml,
};

#[test]
fn detects_xml_and_declarations() {
    let input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root />";
    assert!(looks_like_xml(input));
    assert!(has_xml_declaration(input));
    assert_eq!(strip_xml_declaration(input), "<root />");
}

#[test]
fn extracts_declaration_and_root_element() {
    let declaration = extract_xml_declaration(
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><root />",
    )
    .expect("declaration should parse");
    let root =
        extract_root_element("<?xml version=\"1.0\"?><root id=\"42\" enabled='true'></root>")
            .expect("root element should parse");

    assert_eq!(declaration.version.as_deref(), Some("1.0"));
    assert_eq!(declaration.encoding.as_deref(), Some("UTF-8"));
    assert_eq!(declaration.standalone.as_deref(), Some("yes"));
    assert_eq!(root.name, "root");
    assert_eq!(root.attributes.len(), 2);
}

#[test]
fn extracts_attributes() {
    let attributes = extract_attributes("<item id=\"42\" enabled='true' />");

    assert_eq!(attributes.len(), 2);
    assert_eq!(
        get_attribute("<item id=\"42\" />", "id"),
        Some("42".to_string())
    );
    assert!(has_attribute("<item enabled=\"true\" />", "enabled"));
}

#[test]
fn escapes_and_unescapes_xml() {
    assert_eq!(
        escape_xml("<tag id=\"1\">&</tag>"),
        "&lt;tag id=&quot;1&quot;&gt;&amp;&lt;/tag&gt;"
    );
    assert_eq!(
        unescape_xml("&lt;root&gt;Tom &amp; Jerry&lt;/root&gt;"),
        "<root>Tom & Jerry</root>"
    );
}

#[test]
fn strips_comments() {
    assert_eq!(
        strip_xml_comments("<root><!-- note --><child /></root>"),
        "<root><child /></root>"
    );
}

#[test]
fn handles_malformed_input_gracefully() {
    assert_eq!(extract_xml_declaration("<?xml version=\"1.0\""), None);
    assert_eq!(extract_root_element("<root"), None);
}

#[test]
fn handles_empty_input() {
    assert!(!looks_like_xml("   "));
    assert!(extract_attributes("").is_empty());
}