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
| Function | Signature | Description |
|---|---|---|
valid | xml.valid(s: string) → bool | Whether s is well-formed XML |
pretty | xml.pretty(s: string) → string | Re-indent XML with 2-space indent |
minify | xml.minify(s: string) → string | Strip whitespace between tags |
get | xml.get(s: string, tag: string) → string | Inner text of the first matching element |
attr | xml.attr(s: string, tag: string, attr: string) → string | Value of attr on the first matching element |
toJson | xml.toJson(s: string) → string | Convert XML to a JSON map string |
parse | xml.parse(s: string) → object | Navigable 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