xml

The xml module validates and reformats XML, reads element text and attributes, and converts XML into JSON or a navigable object tree. Import it with import xml.

Functions

FunctionSignatureDescription
validxml.valid(s: string) → boolWhether s is well-formed XML
prettyxml.pretty(s: string) → stringRe-indent XML with 2-space indent
minifyxml.minify(s: string) → stringStrip whitespace between tags
getxml.get(s: string, tag: string) → stringInner text of the first matching element
attrxml.attr(s: string, tag: string, attr: string) → stringValue of attr on the first matching element
toJsonxml.toJson(s: string) → stringConvert XML to a JSON map string
parsexml.parse(s: string) → objectNavigable XML tree (children as fields, attributes prefixed @, text under #text)

Example

import xml

let doc = "<book id=\"1\"><title>Goost</title></book>"
print(xml.get(doc, "title"))            // Goost
print(xml.attr(doc, "book", "id"))      // 1

let tree = xml.parse(doc)
print(tree.book.title["#text"])         // Goost
Standard library · View as Markdown · llms-full.txt