構文が少しずれています。連絡先の新しいテーブルを作成してから、「連絡先」ノードを追加し、このコードで同時に追加のテーブルを割り当てます。
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)
その例に従って、任意の深さまでドリルダウンする方法がかなり明確になるはずです。子タグの作成を簡単に行える関数を記述して、コードの冗長性を大幅に減らすこともできます...