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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With