[英]Variable not accessible outside of function Swift
Here is the problem i am trying to parse XML in Swift everything works except for values. 这是我试图在Swift中解析XML的问题,除了值之外,其他所有东西都有效。
import UIKit
class ItemParser: NSObject, XMLParserDelegate {
var parser = XMLParser()
var element:String!
var currentName:String = String()
func beginParsing()
{
parser = XMLParser(contentsOf:(NSURL(string:"URL"))! as URL)!
parser.delegate = self
parser.parse()
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
element = elementName
}
func parser(_ parser: XMLParser, foundCharacters string: String)
{
if element.isEqual("name") {
currentName = string
}
print (currentName) -- displaying correctly
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
if elementName.isEqual("inv") {
print("begginging")
print(currentName) -- displaying nothing
}
}
To my Understanding i have declared all variable in the correct place but the variable is not retaining outside of function. 据我了解,我已经在正确的位置声明了所有变量,但是该变量并未保留在函数之外。 What am i doing wrong?
我究竟做错了什么?
Since the character value for an XML element can be huge it is possible that foundCharacters
is called multiple times for the same element. 由于XML元素的字符值可能很大,因此可能为同一个元素多次调用
foundCharacters
。 So you have to append the characters to your class variable until didEndElement
is being called for that element: 因此,必须将字符追加到类变量中,直到
didEndElement
元素调用didEndElement
为止:
func parser(_ parser: XMLParser, foundCharacters string: String)
{
if element.isEqual("name") {
currentName += string // append here
}
}
And you have to take care on correctly resetting this variable on a new element: 而且,您必须注意在新元素上正确重置此变量:
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
element = elementName
currentName = "" // reset
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
if elementName.isEqual("inv") {
print("begginging")
print(currentName) // is now complete
}
}
Do NOT forget XML is streaming kind of protocol - what this means is - it does not give you all the information at once, so you need to append to the info you already have. 不要忘记XML是流式协议-这意味着什么-它不会一次为您提供所有信息,因此您需要附加到已经拥有的信息上。 What you need to do in
foundCharacters
is: 您需要在
foundCharacters
做的是:
currentName += string
and renew currentName in start/end of element parsing. 并在元素解析开始/结束时更新currentName。
currentName = ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.