Simple Xml Parser in Swift Language for Mac OSX

By | August 14, 2019

Here is example how to parse the XML file in Swift 4.1.2 Language for Mac OSX, using XMLParser class. During processing XML document XMLParser notifies its delegate about the handled items, such as elements, attributes, CDATA blocks, comments, and so on. The total list of delegate methods is presented here. The example does not use all of them just some to handle starting and ending tags for a given element and element value if any. Beside it is notified by parser about encountering a fatal error. It is console application, the code is:


import Foundation
class XMLDic : NSObject, XMLParserDelegate {
   var level:Int = 0
   func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
      print(“startElement: “, elementName, “, Level: “, level);
      level = level+1
   }
   func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
      level = level – 1
      print(“endElement: “, elementName, “, Level: “, level);
      }

   func parser(_ parser: XMLParser, foundCharacters string: String) {
      let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
      if trimmedString.count > 0
      {
         print(” Value: ” + string);
      }
   }

   func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
//      print(“failure error: “, parseError)
   }
}

print(“xml parser”)
let argsCount = CommandLine.argc
if (argsCount < 2)
{
   print(“specify xml file with path for parsing as an argument”)
   exit(-1)
}
let xmlFile = CommandLine.arguments[1]
print(“xml file \(xmlFile) to parse”)
let fileManager = FileManager()
if !fileManager.fileExists(atPath: xmlFile)
{
   print(“file \(xmlFile) does not exist”)
   exit(-1)
}
let xmlFileURL = NSURL(fileURLWithPath: xmlFile) as URL
var parser = XMLParser(contentsOf: xmlFileURL)!
let xmlDic = XMLDic()
parser.delegate = xmlDic
if parser.parse()
{
   print(“Parsing OK”)
}
else
{
   print(“Parser error: “, parser.parserError, “, line: “, parser.lineNumber, “, column: “, parser.columnNumber);
}



Building from command line:


# xcodebuild -project xmlParserSwift.xcodeproj -configuration Debug

Example of Xml file to parse:


<?xml version=”1.0″ encoding=”UTF-8″?>
<RootData>
 <Key/>
 <Person>
  <ID>100</ID>
  <Name>John Doe</Name>
 </Person>
 <Business>
  <Name>Ladydebug</Name>
  <website>http://ladydebug.com</website>
  <Address>2600 Main Street</Address>
  <City>None</City>
  <Zip>555555</Zip>
 </Business>
 <ExtraData>
  <Description/>
  <ID/>
 </ExtraData>
</RootData>

Result of parsing:


# /Alex/xmlParserSwift/build/Debug/xmlParserSwift xmlData.xml
xml parser
xml file xmlData.xml to parse
startElement: RootData , Level: 0
startElement: Key , Level: 1
endElement: Key , Level: 1
startElement: Person , Level: 1
startElement: ID , Level: 2
  Value: 100
endElement: ID , Level: 2
startElement: Name , Level: 2
  Value: John Doe
endElement: Name , Level: 2
endElement: Person , Level: 1
startElement: Business , Level: 1
startElement: Name , Level: 2
  Value: Ladydebug
endElement: Name , Level: 2
startElement: website , Level: 2
  Value: http://ladydebug.com
endElement: website , Level: 2
startElement: Address , Level: 2
  Value: 2600 Main Street
endElement: Address , Level: 2
startElement: City , Level: 2
  Value: None
endElement: City , Level: 2
startElement: Zip , Level: 2
  Value: 555555
endElement: Zip , Level: 2
endElement: Business , Level: 1
startElement: ExtraData , Level: 1
startElement: Description , Level: 2
endElement: Description , Level: 2
startElement: ID , Level: 2
endElement: ID , Level: 2
endElement: ExtraData , Level: 1
endElement: RootData , Level: 0
Parsing OK

Leave a Reply

Your email address will not be published. Required fields are marked *