XML often arrives escaped inside something else: a JSON field, a database column, a CSV cell. parse-xml() turns the string into a document, parse-xml-fragment() accepts content without a single root, and serialize() goes the other way, with an optional map of output parameters:
xp 'parse-xml("<a>Hello <b>World</b></a>")//b/string()' \
'count(parse-xml-fragment("I say<a>Hello</a> twice")/node())' 'parse-xml("<a>")' \
'serialize(//book[1]/title)'Output
parse-xml("<a>Hello <b>World</b></a>")//b/string() => "World"
count(parse-xml-fragment("I say<a>Hello</a> twice")/node()) => 3
parse-xml("<a>") => error FODC0006
serialize(//book[1]/title) => "<title>The Quiet Harbor</title>"The fragment holds three nodes (text, element, text). parse-xml() fails with FODC0006 on malformed input, so wrap it in try (Error Functions) when a feed may be dirty.
String Parsing Functions
String parsing functions convert between XML text and nodes, and serialize sequences back to text.| parse-xml("<a>Hello <b>World</b></a>") | Creates an XML document from an XML string and returns its root node. |
| parse-xml-fragment("I say<a>Hello <b>World</b></a>") | Creates an XML fragment from a string and returns its root node. Unlike parse-xml(), this does not raise an error even though the input is not well-formed XML on its own (it has no single root element). |
| serialize(1 to 3) | Returns a serialized string representation of the sequence, with items separated by a single space. |
merged-01-01-ch03-string-parsing-functions.xpath.txt
serialize(1 to 3)
Output
1 2 3