2012-05-07 75 views
2

我正在使用luaxml將Lua錶轉換爲xml。我有使用luaxml一個問題,例如,我有喜歡這個使用luaxml將Lua表解析爲Xml

t = {name="John", age=23, contact={email="[email protected]", mobile=12345678}} 

當我試圖用LuaXML一個Lua表,

local x = xml.new("person") 
x:append("name")[1] = John 
x:append("age")[1] = 23 
x1 = xml.new("contact") 
x1:append("email")[1] = "[email protected]" 
x1:append("mobile")[1] = 12345678 
x:append("contact")[1] = x1 

生成的XML變成:

<person> 
    <name>John</name> 
    <age>23</age> 
    <contact> 
    <contact> 
     <email>[email protected]</email> 
     <mobile>12345678</mobile> 
    </contact> 
    </contact> 
</person>` 

xml中有2個聯繫人。我該怎麼做才能使Xml正確?

另外,如何將XML轉換回Lua表?

回答

2

你的語法只是有點過了,你要創建一個新表的聯繫人,然後附加一個「聯繫人」節點,並在同一時間,這個碼附加額外的一個:

x1 = xml.new("contact") 
x1:append("email")[1] = "[email protected]" 
x1:append("mobile")[1] = 12345678 
x:append("contact")[1] = x1 

應該真的只是是這樣的:

local contact = xml.new("contact") 
contact.email = xml.new("email") 
table.insert(contact.email, "[email protected]") 

contact.mobile = xml.new("mobile") 
table.insert(contact.mobile, 12345678) 

請記住,每個「節點」是自己的表值,這就是xml.new()返回。

下面的代碼在您撥打xml.save(x, "\some\filepath")時會正確創建xml。需要記住的是,無論何時調用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, "[email protected]") 

-- 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) 

它應該變得相當清楚下面的例子,你可以深入任意鑽取。你甚至可以編寫函數,以方便地創建子標籤,使代碼更簡潔...

0
local x = xml.new("person") 
x:append("name")[1] = John 
x:append("age")[1] = 23 
x1 = x:append("contact") 
x1:append("email")[1] = "[email protected]" 
x1:append("mobile")[1] = 12345678 

print(x)