app.xml - XML 解析与生成 API
XML 文档解析和生成。
权限级别: L0(安全,始终可用)
方法
app.xml.parse(text)
解析 XML 文本为 DOM 树。
参数:
text(string) - XML 文本
返回值: table, error - DOM 树结构
返回的节点结构:
tag(string) - 元素标签名attributes(table, 可选) - 属性字典text(string, 可选) - 文本内容children(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)
读取并解析 XML 文件。
参数:
path(string) - XML 文件路径
返回值: table, error
local doc, err = app.xml.parseFile("/path/to/config.xml")
app.xml.generate(doc)
从 DOM 树生成 XML 文本。
参数:
doc(table) - DOM 树结构(同parse()返回格式)
返回值: 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>...
示例
修改 XML 配置文件
function MyPlugin:handleUpdateConfig(context)
local file = context.selectedFiles[1]
local doc, err = app.xml.parseFile(file)
if not doc then
app.dialog.alert("错误", err)
return
end
-- 遍历并修改
if doc.children then
for _, child in ipairs(doc.children) do
if child.tag == "version" then
child.text = "2.0"
end
end
end
-- 写回文件
local xml = app.xml.generate(doc)
if xml then
app.file.write(file, xml)
app.notification.show("完成", "配置已更新")
end
end