George White
George White

Reputation: 125

Generating XML element with attributes in Swift

I'm learning Swift and started a small project to read in a csv file and emit an XML file. I have this code -

import Cocoa
import Foundation


let base = XMLElement(name: "root")
let fcpxxml = XMLDocument(rootElement: base)
var build =  XMLElement(name: "clip", stringValue:"myClip" )
base.addChild(build)
print(fcpxxml.xmlString)

it outputs -

<root><clip>myClip</clip></root>

I need to add attributes. In the Apple developer documentation I see element(withName:children:attributes:)

I tried to use it to create an element started with nil attributes -

var base1 = element(withName name: "angle", children: nil, attributes: nil )

I get error

Use of unresolved identifier 'element'

I do not see why this doesn't work and am looking for an example of code that will let me produce -

<root><clip name = "myClip"> </clip></root>

Upvotes: 1

Views: 1461

Answers (1)

Sweeper
Sweeper

Reputation: 270980

You seem to be looking for this method - attribute(withName:stringValue:). It returns an XMLNode, which you can add to an XMLElement using addAttribute.

let base = XMLElement(name: "root")
let fcpxxml = XMLDocument(rootElement: base)
let build =  XMLElement(name: "clip", stringValue:"")
build.addAttribute(XMLNode.attribute(withName: "name", stringValue: "myClip") as! XMLNode)
base.addChild(build)
print(fcpxxml.xmlString) // <root><clip name="myClip"></clip></root>

The method you found, element(withName:children:attributes:) could also be used to create your XML, but it needs a lot of casting.

let base = XMLNode.element(withName: "root", children: [
    XMLNode.element(withName: "clip",
                    children: nil,
                    attributes: [
                        XMLNode.attribute(withName: "name", stringValue: "myClip") as! XMLNode
                    ]) as! XMLNode
], attributes: nil) as! XMLNode

Upvotes: 1

Related Questions