Sample code for 30+ languages & platforms
Lua

AddAttribute - Insert New Attribute in an XML Node

Demonstrates adding an name=value attribute to an XML element.

This example uses the XML sample file here: sample1.xml. The sample1.xml file contains this content:

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local xml = chilkat.Xml.new()

local success = xml:load_xml_file("qa_data/xml/sample1.xml")
if not success then
    print(xml.last_error_text)
    return
end

-- Navigate to the "books" element:
local bFound = xml:find_child2("books")
if not bFound then
    print("No books child found!")
    return
end

local numChildren = xml.num_children

local i = 0
while i < numChildren do
    -- Navigate to the Nth book
    xml:get_child2(i)

    -- Display the book title:
    print(xml:get_attr_value("title"))

    -- Add a new integer attribute:
    -- Should never fail..
    xml:add_attribute_int("bookId", i)

    -- Add a new unread="yes" attribute:
    xml:add_attribute("unread", "yes")

    -- Navigate back up to the parent:
    xml:get_parent2()

    i = i + 1
end

-- Navigate back to the document root:
xml:get_root2()

-- Save the updated document:
success = xml:save_xml("modified.xml")
if not success then
    print(xml.last_error_text)
    return
end

print(xml:get_xml())