2

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テーブルに戻すにはどうすればよいですか?

4

2 に答える 2

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)

各「ノード」は独自のテーブル値であり、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)

その例に従って、任意の深さまでドリルダウンする方法がかなり明確になるはずです。子タグの作成を簡単に行える関数を記述して、コードの冗長性を大幅に減らすこともできます...

于 2012-05-08T02:21:29.687 に答える
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)
于 2014-09-30T01:34:35.483 に答える