如何解析XML-Swift 3中的复杂XML构造

时间:2018-07-25 13:02:21

标签: swift xml parsing

我必须在应用程序中解析xml文件。我从Web服务使用令牌获取xml数据。我无法解析真正的xml标记的数据,因为xml文件是一个复杂的结构,并且一些标记会重复几次。例如,xml文件具有17个“ cbc:ID”标签。我需要先将cbc:ID标记插入“发票”标记。 This an example用于我的xml数据。我使用该功能;

func getXMLDataFromServer(authorization:String){
        let url = NSURL(string: self.urlString)
        let request = NSMutableURLRequest(url: url! as URL)
        request.httpMethod = "GET"
        request.addValue(authorization, forHTTPHeaderField: "Authorization")
        let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in

            if error != nil {
                //print("\(error)")
            }

            else {

                let htmlContent = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                //print("\(htmlContent)")

            }
            if let receivedData = data {
                if let aString = String(data: receivedData, encoding: String.Encoding.utf8) {
                    if let percentage = aString.addingPercentEncoding(withAllowedCharacters:CharacterSet(charactersIn:"ıİöÖçÇüÜğĞşŞ").inverted) {
                        if let aData = percentage.data(using: String.Encoding.utf8) {
                            let parser = XMLParser(data: aData)
                            parser.delegate = self
                            parser.parse()
                        }
                    }
                }
            }
        }
        task.resume()
    }
//MARK:- XML Delegate methods
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?,
     

attributes attributeDict:[String:String] = [:]){           currentParsingElement = elementName           如果elementName ==“发票” {               print(“开始解析...”)           }           打印(elementName)       }

func parser(_ parser: XMLParser, foundCharacters string: String) {
    let foundedChar = string.trimmingCharacters(in:NSCharacterSet.whitespacesAndNewlines)

    if (!foundedChar.isEmpty) {
        if currentParsingElement == "cbc:ID" {
            ipAddr += foundedChar
        }
        else if currentParsingElement == "cbc:Name" {
            countryCode += foundedChar
        }
        else if currentParsingElement == "CountryName" {
            countryName += foundedChar
        }

    }
    print(foundedChar)
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "Invoice" {
        print("Ended parsing...")
    }

    print(elementName)

}

func parserDidEndDocument(_ parser: XMLParser) {
    DispatchQueue.main.async {
        // Update UI
        //self.displayOnUI()

    }
}

func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
    print("parseErrorOccurred: \(parseError)")
}

我已经尝试that tutorial来解析我的xml数据。但是,我无法解析xml数据中的true标记。

我需要一些标签的数据,在“发票”标签中有“ cbc:ID”标签的数据, “ cac:AccountingCustomerParty”标签中的“ cbc:Name”标签数据, 再次使用“ cbc:ID”标记,但它已放入“ cac:AccountingCustomerParty” 和“ cac:LegalMonetaryTotal”中的“ cbc:PayableAmount”标记的数据

有人知道如何为我的应用程序解析真实标签的数据吗?

1 个答案:

答案 0 :(得分:0)

使用XMLParser解析如此复杂的XML非常困难。

如果您不介意使用外部库,则可以尝试XMLMapper

实际上,使用嵌套映射很容易。您可以具有以下模型类:

class Invoice: XMLMappable {
    var nodeName: String!

    var cbcID: String?
    var partyName: String?
    var partyCBCID: PartyCBCID?
    var payableAmount: PayableAmount?

    required init?(map: XMLMap) { }

    func mapping(map: XMLMap) {
        cbcID <- map["cbc:ID"]
        partyName <- map["cac:AccountingCustomerParty.cac:Party.cac:PartyName.cbc:Name"]
        partyCBCID <- map["cac:AccountingCustomerParty.cac:Party.cac:PartyIdentification.cbc:ID"]
        payableAmount <- map["cac:LegalMonetaryTotal.cbc:PayableAmount"]
    }

}

class PartyCBCID: XMLMappable {
    var nodeName: String!

    var schemeID: String?
    var id: String?

    required init?(map: XMLMap) { }

    func mapping(map: XMLMap) {
        schemeID <- map.attributes["schemeID"]
        id <- map.innerText
    }

}

class PayableAmount: XMLMappable {
    var nodeName: String!

    var currencyID: String?
    var amount: Double?

    required init?(map: XMLMap) { }

    func mapping(map: XMLMap) {
        currencyID <- map.attributes["currencyID"]
        amount <- map.innerText
    }
}

,您可以使用map(XMLString:)的{​​{1}}函数来映射XML字符串,例如:

XMLMapper

尝试一下。