漂亮的打印 XML 和 Swift 3

Pretty print XML with Swift 3

使用Swift 2.2 我曾经这样美化XML:

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

// ...

let data = xml.XMLDataWithOptions(NSXMLNodePrettyPrint | NSXMLNodeCompactEmptyElement)

不幸的是,Swift 3 无法再使用此代码(由 Xcode 8[=29 自动转换=]):

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

// ...

let data = xml.xmlData(withOptions: NSXMLNodePrettyPrint)

它产生以下错误:

Use of unresolved identifier 'NSXMLNodePrettyPrint'

好像in/out选项变了但是不太清楚怎么用:https://developer.apple.com/reference/foundation/xmldocument/input_and_output_options

有什么想法吗?

xmlData(withOptions:) accepts XMLNode.Options,但他们必须 转换为 Int:

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

或多个选项:

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

Swift 4 开始, xmlData(withOptions:) 需要一个 XMLNode.Options 参数,所以这简化为

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

单个选项,或

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

多个选项。

Swift 4.2 :

if let xml = try? XMLElement.init(xmlString:"<A><b>test</b><c>test</c></A>") {
   let data = xmlDoc.xmlData(options:.nodePrettyPrint)
   let str = String(data: data, encoding: .utf8)!
   print(str)
}

//Output:
<A>
   <b>test</b>
   <c>test</c>
</A>

不应该是:

func prettyFormat(xmlString:String) -> String? {
  do {
    let xml = try XMLDocument.init(xmlString: xmlString)
    let data = xml.xmlData(options: .nodePrettyPrint)
    let str:String? = String(data: data, encoding: .utf8)
    return str
  }
  catch {
    print (error.localizedDescription)
  }
  return nil
}

用法:

var str = "Hello, XML Pretty Format playground"
let testStr:String? = "<A><b>test</b>  <c>test</c><d>\(str)</d></A>  "


let aStr = prettyFormat(xmlString: "<A><b>test</b>  <c>test</c><d>\(str)</d></A>  ")
print (aStr ?? "?")

let bStr = prettyFormat(xmlString:testStr!)
print (bStr ?? "?")

XMLElement.init 不工作... 请改进..