Antiokhos
Antiokhos

Reputation: 3055

xml parsing is done but the values are not added to the array in swift

    <?xml version="1.0"?>
<account>
  <username>dedehakan</username>
  <avatar>http://www.somewebsite.com/empty.png</avatar>
  <email>[email protected]</email>
  <points>450</points>
  <type>premium</type>
  <expiration>666666</expiration>
  <expiration-txt>17/12/2014 20:37:35</expiration-txt>
  <premium-left>-614239</premium-left>
</account>

i want to parse this with nsxmlparser. I get parsing done correctly how ever didnt get any values. here what i try:

var mydata:NSData = resp.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var xmlParser = NSXMLParser(data: mydata)
xmlParser.delegate = self
xmlParser.parse()

resp is string and the value of resp is xml text.

func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) {
    println(elementName)
    println(attributeDict)
}

The output is:

account
nil
username
nil
avatar
nil
email
nil
....

The question is how i get the values in xml string?

Upvotes: 1

Views: 193

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

The problem is that the data in your XML document does not come from attributes; it comes from the textual content of the tag itself. That is why you get all these nils when you print attributeDict.

To fix this, you need to do these four things:

  • Add an instance variables lastTag:String? and tagContent:String? to your parser delegate class
  • Set lastTag to elementName in the didStartElement function
  • Provide an implementation of the foundCharacters function that appends characters to tagContent string
  • Provide an implementation of didEndElement function which uses the tag and the content in whatever way that you need, and then sets them both to nil.

To make a long story short, you need to wait until the content of the tag has become available until you reach the end tag, at which point you could "harvest" the content from instance variables.

Upvotes: 1

Related Questions