app.xml - XML Parsing & Generation API
XML document parsing and generation.
Permission level: L0 (safe, always available)
Methods
app.xml.parse(text)
Parses XML text into a DOM tree.
Parameters:
text(string) - XML text
Returns: table, error - DOM tree structure
Returned node structure:
tag(string) - Element tag nameattributes(table, optional) - Attribute dictionarytext(string, optional) - Text contentchildren(array, optional) - Child element array
local doc, err = app.xml.parse([[
<root>
<item id="1" type="a">Hello</item>
<item id="2">World</item>
</root>
]])
-- {
-- tag = "root",
-- children = {
-- {tag = "item", attributes = {id = "1", type = "a"}, text = "Hello"},
-- {tag = "item", attributes = {id = "2"}, text = "World"}
-- }
-- }
app.xml.parseFile(path)
Reads and parses an XML file.
Parameters:
path(string) - XML file path
Returns: table, error
local doc, err = app.xml.parseFile("/path/to/config.xml")
app.xml.generate(doc)
Generates XML text from a DOM tree.
Parameters:
doc(table) - DOM tree structure (same format as returned byparse())
Returns: string, error
local xml = app.xml.generate({
tag = "config",
children = {
{tag = "name", text = "MyApp"},
{tag = "version", text = "1.0"},
{tag = "settings", children = {
{tag = "theme", attributes = {mode = "dark"}, text = "blue"}
}}
}
})
-- <?xml version="1.0" encoding="UTF-8"?>
-- <config><name>MyApp</name><version>1.0</version>...
Examples
Modify an XML configuration file
function MyPlugin:handleUpdateConfig(context)
local file = context.selectedFiles[1]
local doc, err = app.xml.parseFile(file)
if not doc then
app.dialog.alert("Error", err)
return
end
-- Traverse and modify
if doc.children then
for _, child in ipairs(doc.children) do
if child.tag == "version" then
child.text = "2.0"
end
end
end
-- Write back to file
local xml = app.xml.generate(doc)
if xml then
app.file.write(file, xml)
app.notification.show("Done", "Configuration updated")
end
end