使用luaxml将Lua表解析为Xml

时间:2012-05-07 14:59:42

标签: lua luaxml

我使用luaxml将Lua表转换为xml。我使用luaxml时遇到问题,例如,我有一个像这样的lua表

t = {name="John", age=23, contact={email="john@gmail.com", mobile=12345678}}

当我尝试使用LuaXML时,

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

生成的xml变为:

<person> 
  <name>John</name>
  <age>23</age>
  <contact>
    <contact>
      <email>john@gmail.com</email>
      <mobile>12345678</mobile>
    </contact>
  </contact>
</person>`

xml中有2个联系人。我该怎么做才能使Xml正确?

此外,如何将XML转换回Lua表?

2 个答案:

答案 0 :(得分:2)

您的语法有点偏离,您正在为联系人创建一个新表,然后附加一个“联系人”节点并使用此代码同时分配另一个节点:

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)

请记住,每个'node'都是它自己的表值,这是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, "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)

在这个例子之后,你应该可以很清楚地深入挖掘它。你甚至可以编写函数来轻松创建子标签,使代码更简洁......

答案 1 :(得分:0)

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

print(x)