gpt4 book ai didi

ios - 从 iOS Swift 中的 xml 文本文件中提取 Json

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:56 25 4
gpt4 key购买 nike

我必须从文本文件中提取和解析 json,我知道如何解析 json,但我无法从 xml 格式中正确提取它。这是我的 xml,其中包含 json。

<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”}]"

最佳答案

解析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 = ""
}
}

关于ios - 从 iOS Swift 中的 xml 文本文件中提取 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44695043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com