14

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 2

15

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)
Sign up to request clarification or add additional context in comments.

6 Comments

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>
@Nuno See the documentation of NSXMLElement. The “options” are called “attributes” – there are many methods to manipulate them.
Thanks for the help. But anyway I just found out that it doesn't work on IOS so I need to find another solution.
This gives me a compile error: "Use of unresolved identifier NSXMLElement"
NSXMLDocument only applies to OS X (as of now). Are there any standard apis for iOS ?
|
10

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

@tadija - Looks like this library is having compatibility issues with SwiftyJSON. As soon as I installed it using cocoapods the build started failing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.