manoelcampos / xml2lua

XML Parser written entirely in Lua that works for Lua 5.1+. Convert XML to and from Lua Tables 🌖💱

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to add an attribute to a node?

jpotts18 opened this issue · comments

Trying to generate an attribute in my xml but not quite sure. I'm a beginner at lua so it may be obvious.

local xml2lua = require("xml2lua")
local people = {
    person = {
        {name="Manoel", city="Palmas-TO"},
        {name="Breno", city="Palmas-TO"}
    }
}
people.id = 1
people.planet = 'earth'

print(xml2lua.toXml(people, "people"))

Actual Output

<people>
<id>1</id>
<planet>earth</planet>
  <person>
    <city>Palmas-TO</city>
    <name>Manoel</name>
  </person>
  <person>
    <city>Palmas-TO</city>
    <name>Breno</name>
  </person>
</people>

Desired Output

<people id="1" planet="earth">
  <person>
    <city>Palmas-TO</city>
    <name>Manoel</name>
  </person>
  <person>
    <city>Palmas-TO</city>
    <name>Breno</name>
  </person>
</people>

If you want tag attributes, add a "_attr" inner table where you desire.
However, in your example, it's strange that all your people have the same id.

I'm wondering if you want somethink like this:

local people = {
    person = {
        {name="Manoel", city="Palmas-TO", _attr = {id = 1, planet = 'earth'}},
        {name="Breno", city="Palmas-TO",  _attr = {id = 2, planet = 'earth'}}
    }
}

@manoelcampos that is exactly what I was looking for! Thanks. Would this be helpful to add to README?

Thanks. It would.