Crate inline_xml

source ·
Expand description

Embed XML data directly in your Rust code.

Example

use inline_xml::xml;

let x = xml! {
    <root>
        <config name="name">John Doe</config>
        <config name="age">42</config>
    </root>
};

How to use

Use the xml! {..} macro to embed XML-structured data directly into your Rust code. During the compile-time of your Rust program, the content inside of your xml! invocations will be checked and converted into an instance of Xml. This makes sure that all invocations of the xml! macro are guaranteed to be valid XML at runtime.

Note on xml! vs xml_tag!

The xml! {..} macro allows multiple top-level tags. If this is not desired, please use the xml_tag! {..} macro.

Dynamic Data

You can include dynamically-generated data into the xml! macro. This can be achieved by putting your Rust code (eg. variables) into {..}.

Example

use inline_xml::xml;

let x = 3;
let y = 2;
let xml = xml! {
    <p>{x} + {y} = {x + y}</p>
};

Bugs and Workarounds

Whitespace

At the moment of writing, proc_macro_span is not stabilized, therefore the macro can’t know about any whitespace used inside of the macro invocation, because the Rust’s token tree parser ignores all whitespace.

Consider the following example:

use inline_xml::xml;

let xml = xml! { <p>Hello World!</p> };
println!("{xml}");

A reasonably thinking person would expect the output to be <p>Hello World!</p>, but instead it would be:

<p>
    Hello
    World
    !
</p>

or <p>Hello World !</p>, depending on how the formatter is implemented.

Supported XML syntax

  • “Normal” tags (<tag>inner</tag>)
  • “Empty tags” (<tag />)
  • Attributes (<tag attr="value" />)
  • Namespaces in Tag names (<ns:tag />)
  • Namespaces in Attr names (<tag ns:attr="value" />)

Extensions

  • Dynamic tag body (<tag>Hello {text}</tag>)
  • Dynamic attr values (<tag attr={value} />)
  • Escaping strings (<tag>"<Hello> \"World\"&"</tag>)

Unsupported XML syntax

  • XML declarations (<?xml version="1.0" encoding="UTF-8"?>)
  • DTD declarations (<!DOCTYPE html>)
  • Probably a little more…

Macros

  • Generate an Xml struct from XML. This macro allows specifying multiple XML root nodes. If you only want a single XML node, please use xml_tag.
  • This macro is similar to xml! {}, but instead of generating an Xml struct, it generates a single Tag.

Structs

Enums

Traits

  • Collect XML from an iterator.
  • This trait must be implemented on types, before they can be used inside the xml! {..} macro.