我必须从文本文件中提取和解析json,我知道如何解析json但我无法从xml格式正确提取它。这是我的包含json的xml。
<Data>
<Persons>[{"ID":"2","Name":"Catagory 1"},{"ID":"3","Name":"Catagory 2”</Persons>
<class>[{"ID":"3","Name":"WEAVING”}]</class>
</Data>
我想要的是让json与其标签分开,例如。
"Persons":"[{"ID":"2","Name":"Catagory 1"},{"ID":"3","Name":"Catagory 2”}]"
答案 0 :(得分:1)
请在下面找到解析xml的示例代码:
import UIKit
import Foundation
class ViewController: UIViewController {
var parser:XMLParser?
var foundChars: String = ""
var personsStr: String = ""
override func viewDidLoad() {
super.viewDidLoad()
parseXML()
// Do any additional setup after loading the view, typically from a nib.
}
func parseXML() {
let str: NSString = "<Data><Persons>[{\"ID\":\"2\",\"Name\":\"Catagory 1\"},{\"ID\":\"3\",\"Name\":\"Catagory 2\"}]</Persons><class>[{\"ID\":\"3\",\"Name\":\"WEAVING\"}]</class></Data>"
if let data = str.data(using: String.Encoding.utf8.rawValue) {
parser = XMLParser.init(data: data)
parser!.delegate = self
parser!.parse()
}
}
}
extension ViewController: XMLParserDelegate {
public func parserDidEndDocument(_ parser: XMLParser) {
debugPrint("Person str is:: " + self.personsStr)
//TODO: You have to build your json object from the PersonStr now
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
self.foundChars = self.foundChars + string
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
debugPrint("end element::" + elementName)
if (elementName == "Persons") {
self.personsStr = self.foundChars
}
self.foundChars = ""
}
}