使用luaxml将Lua表解析为Xml

问题描述:

我正在使用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表?

你的语法只是有点过了,你要创建一个新表的联系人,然后附加一个“联系人”节点,并在同一时间,这个码附加额外的一个:

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) 

它应该变得相当清楚下面的例子,你可以深入任意钻取。你甚至可以编写函数,以方便地创建子标签,使代码更简洁...

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)