检查Swift中是否存在XML元素

时间:2018-02-26 20:55:27

标签: ios swift nsxmlparser

我需要检查我的XML中是否存在从调用Web服务中检索到的元素。如果某个特定元素不存在,我需要运行某个函数。

这是我到目前为止所拥有的。如果所有这些元素都在那里,这就有效。我需要确保" MembershipNumber"元素存在。

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

    attributes = attributeDict as NSDictionary

    element = elementName
    if ((elementName as NSString).isEqual(to: "MembershipInfo")) {
        paidYear = ""
        county = ""
        name = ""
        dueDateString = ""
        membershipNumber = ""
    }
}

func parser(_ parser: XMLParser, foundCharacters string: String) {
    if element == "MembershipNumber" {
        membershipNumber.append(string)
        print("NUMBER: \(membershipNumber)")
    }
    if element == "County" {
        let counties = Counties().counties
        county.append(counties[string]!)
        print("COUNTY: \(county)")
    }

    if element == "PaidYear" {
        paidYear.append(string)
        print("PAID YEAR: \(paidYear)")
    }

    if element == "DueDate" {
        dueDateString.append(string)
        print("Due Date: \(dueDateString)")
    }

    if element == "Name" {
        if name == "" {
            name.append(string)
            print("NAME: \(name)")
        }
    }
}

1 个答案:

答案 0 :(得分:2)

didStartElement内的所有元素的名称存储在数组中,直到此方法调用

 optional func parserDidEndDocument(_ parser: XMLParser)

然后检查该元素名称的数组内容