Karl Kivi
Karl Kivi

Reputation: 145

XML Parse swift accessing attributeDict

How can I get access to AttributeDict in parser function to get columns(name, short and day)? (code is below) I tried something, but it's not working and not finding any help from google either.

Here's the xml file:

<?xml version="1.0" encoding="windows-1257"?>
<timetable ascttversion="2015.5.5" importtype="database" options="daynumbering1,idprefix:Oman" displayname="Oman XML" displaycountries="om" displayinmenu="0">


   <days options="canadd,canremove,canupdate,silent" columns="name,short,day">

      <day name="Esmasp‰ev" short="Es" day="1"/>
      <day name="Teisip‰ev" short="Te" day="2"/>
      <day name="Kolmap‰ev" short="Ko" day="3"/>
      <day name="Neljap‰ev" short="Ne" day="4"/>
      <day name="Reede" short="Re" day="5"/>
   </days>
</timetable>

Here is the function:

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
    elementName
    print("\(elementName)")
//    if attributeDict == ["Name" : "Esmaspäev"] {
//        print("\(attributeDict)")
//    }
    if elementName == "day"
    {
        if elementName == "day"{
            passName=true;
        }
        passData=true;
    }
}

Upvotes: 1

Views: 636

Answers (1)

cezheng
cezheng

Reputation: 564

import Fuzi

func parse() {
    do {
        // Read the xml file as String
        guard 
            let path = NSBundle.mainBundle().pathForResource("arvestusDays", ofType: "xml")
        else {
            print("XML file does not exist.")
            return
        }
        let xmlString = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)

        // Parse the xml string
        let doc = try XMLDocument(string: xmlString)

        if let days = doc.root.firstChild(tag: "days") {
            for day in days.children {
                print(day["name"])
                print(day["short"])
                print(day["day"])
            }
        }
    } catch let error {
        print(error)
    }
}

I don't have a Mac with me right now so I can't run to test it, but this code should work. Comment in case it doesn't.

UPDATE:

In case you have encoding problems, try creating the XMLDocument from NSData rather than from String:

        let xmlData = NSData(contentsOfFile: path)

        // Parse the xml string
        let doc = try XMLDocument(data: xmlData!)

Upvotes: 2

Related Questions