How can I create XML files "manually" using swift? Is there any library that I can use? I saw that in objc it's possible to add libxml but even with that I can't find any good documentation on it. Any suggestions?
2 Answers
You could use XMLDocument to write XML. For example:
import Foundation
let root = XMLElement(name: "root")
let xml = XMLDocument(rootElement: root)
root.addChild(XMLElement(name: "foo", stringValue:"bar"))
print(xml.xmlString)
6 Comments
Nuno
just one more question, if I want on the root to add some more stuf like option how would I do? The output that I want is smth like <root "some option here"></root>
Arkku
@Nuno See the documentation of
NSXMLElement. The “options” are called “attributes” – there are many methods to manipulate them.Nuno
Thanks for the help. But anyway I just found out that it doesn't work on IOS so I need to find another solution.
Tim Scott
This gives me a compile error: "Use of unresolved identifier NSXMLElement"
Feru
NSXMLDocument only applies to OS X (as of now). Are there any standard apis for iOS ?
|
I made this new simple and lightweight XML parser for iOS in Swift - AEXML
You can use it to read XML data like this:
let someValue = xmlDocument["element"]["child"]["anotherChild"].value
or you can use it to build XML string like this:
let document = AEXMLDocument()
let element = document.addChild("element")
element.addChild("child")
document.xmlString // returns XML string of the entire document structure
NSXMLDocument works for OSX, but does not exist on iOS, so this will help in that case.
1 Comment
Nital
@tadija - Looks like this library is having compatibility issues with SwiftyJSON. As soon as I installed it using cocoapods the build started failing