您的语法有点偏离,您正在为联系人创建一个新表,然后附加一个“联系人”节点并使用以下代码同时分配一个额外的节点:
x1 = xml.new("contact")
x1:append("email")[1] = "john@gmail.com"
x1:append("mobile")[1] = 12345678
x:append("contact")[1] = x1
这实际上应该是这样的:
local contact = xml.new("contact")
contact.email = xml.new("email")
table.insert(contact.email, "john@gmail.com")
contact.mobile = xml.new("mobile")
table.insert(contact.mobile, 12345678)
请记住,每个“节点”都是它自己的表值,这是 xml.new() 返回的值。
以下代码在您调用时正确创建 xml xml.save(x, "\some\filepath")
。要记住的是,每当你调用 xml.new() 时,你都会得到一个表,我认为那里的决定是它可以很容易地设置属性......但是使添加简单值的语法更加冗长.
-- generate the root node
local root = xml.new("person")
-- create a new name node to append to the root
local name = xml.new("name")
-- stick the value into the name tag
table.insert(name, "John")
-- create the new age node to append to the root
local age = xml.new("age")
-- stick the value into the age tag
table.insert(age, 23)
-- this actually adds the 'name' and 'age' tags to the root element
root:append(name)
root:append(age)
-- create a new contact node
local contact = xml.new("contact")
-- create a sub tag for the contact named email
contact.email = xml.new("email")
-- insert its value into the email table
table.insert(contact.email, "john@gmail.com")
-- create a sub tag for the contact named mobile
contact.mobile = xml.new("mobile")
table.insert(contact.mobile, 12345678)
-- add the contact node, since it contains all the info for its
-- sub tags, we don't have to worry about adding those explicitly.
root.append(contact)
遵循该示例,您应该可以清楚地了解如何任意深入研究。您甚至可以编写函数来轻松创建子标签,从而使代码不那么冗长......