使用Swift 3的漂亮打印XML

时间:2016-09-13 11:03:59

标签: xml swift swift3 pretty-print

使用 Swift 2.2 ,我曾经像那样美化XML:

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

// ...

let data = xml.XMLDataWithOptions(NSXMLNodePrettyPrint | NSXMLNodeCompactEmptyElement)

不幸的是,使用此代码不再使用 Swift 3 (由 Xcode 8 自动转换):

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

// ...

let data = xml.xmlData(withOptions: NSXMLNodePrettyPrint)

它会产生以下错误:

Use of unresolved identifier 'NSXMLNodePrettyPrint'

似乎输入/输出选项已更改但不清楚如何使用它:https://developer.apple.com/reference/foundation/xmldocument/input_and_output_options

有什么想法吗?

3 个答案:

答案 0 :(得分:8)

xmlData(withOptions:)接受XMLNode.Options,但必须是gem 'google_drive' 转换为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])

有多种选择。

答案 1 :(得分:1)

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>

答案 2 :(得分:0)

那不是:

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无法正常工作... 请改善..