检查 XML 元素是否存在于 Swift 中
Check if XML Element Exists in Swift
我需要检查我的 XML 中是否存在通过调用网络服务检索到的元素。如果特定元素不存在,我需要 运行 特定功能。
这是我目前所掌握的。如果所有这些元素都存在,这将起作用。我需要确保 "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)")
}
}
}
将didStartElement
中所有元素的名称存储在一个数组中,直到此方法被调用
optional func parserDidEndDocument(_ parser: XMLParser)
然后检查该元素名称的数组内容
你可以很好地 XML 解析 Fuzi。
从 XML 字符串中获取 XML 文档:
guard let xml = try? XMLDocument(string: xmlString) else {
return
}
获取 XML 元素 XPath 如果存在:
guard let membershipNumber = xml.firstChild(xpath: "/MembershipNumber") else {
return
}
我需要检查我的 XML 中是否存在通过调用网络服务检索到的元素。如果特定元素不存在,我需要 运行 特定功能。
这是我目前所掌握的。如果所有这些元素都存在,这将起作用。我需要确保 "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)")
}
}
}
将didStartElement
中所有元素的名称存储在一个数组中,直到此方法被调用
optional func parserDidEndDocument(_ parser: XMLParser)
然后检查该元素名称的数组内容
你可以很好地 XML 解析 Fuzi。
从 XML 字符串中获取 XML 文档:
guard let xml = try? XMLDocument(string: xmlString) else {
return
}
获取 XML 元素 XPath 如果存在:
guard let membershipNumber = xml.firstChild(xpath: "/MembershipNumber") else {
return
}