Swift
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
let xml = CkoXml()!
success = xml.loadFile(path: "qa_data/xml/sample1.xml")
if success != true {
print("\(xml.lastErrorText!)")
return
}
// Navigate to the "books" element:
var bFound: Bool = xml.findChild2(tagPath: "books")
if bFound == false {
print("No books child found!")
return
}
var numChildren: Int = xml.numChildren.intValue
var i: Int = 0
while i < numChildren {
// Navigate to the Nth book
xml.getChild2(index: i)
// Display the book title:
print("\(xml.getAttrValue(name: "title")!)")
// Add a new integer attribute:
// Should never fail..
xml.addAttributeInt(name: "bookId", value: i)
// Add a new unread="yes" attribute:
xml.addAttribute(name: "unread", value: "yes")
// Navigate back up to the parent:
xml.getParent2()
i = i + 1
}
// Navigate back to the document root:
xml.getRoot2()
// Save the updated document:
success = xml.save(path: "modified.xml")
if success != true {
print("\(xml.lastErrorText!)")
return
}
print("\(xml.getXml()!)")
}