Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty print XML with Swift 3

With Swift 2.2 I used to prettify XML like that:

let detxTag = NSXMLElement(name: "detx")
let xml = NSXMLDocument(rootElement: detxTag)

// ...

let data = xml.XMLDataWithOptions(NSXMLNodePrettyPrint | NSXMLNodeCompactEmptyElement)

Unfortunately, it is not possible with Swift 3 anymore with this code (automatically converted by Xcode 8):

let detxTag = XMLElement(name: "detx")
let xml = XMLDocument(rootElement: detxTag)

// ...

let data = xml.xmlData(withOptions: NSXMLNodePrettyPrint)

It produces the following error:

Use of unresolved identifier 'NSXMLNodePrettyPrint'

It seems that in/out options have changed but it is not very clear how to use it: https://developer.apple.com/reference/foundation/xmldocument/input_and_output_options

Any idea?

like image 721
Martin Delille Avatar asked Dec 11 '22 15:12

Martin Delille


1 Answers

xmlData(withOptions:) accepts XMLNode.Options, but they must be converted to an Int:

let data = xml.xmlData(withOptions: Int(XMLNode.Options.nodePrettyPrint.rawValue))

or for multiple options:

let options: XMLNode.Options = [.nodePrettyPrint, .nodeCompactEmptyElement]
let data = xml.xmlData(withOptions: Int(options.rawValue))

As of Swift 4, xmlData(withOptions:) takes a XMLNode.Options argument, so this simplifies to

let data = xml.xmlData(options: .nodePrettyPrint)

for a single option, or

let data = xml.xmlData(options: [.nodePrettyPrint, .nodeCompactEmptyElement])

for multiple options.

like image 112
Martin R Avatar answered Jan 17 '23 00:01

Martin R