2014-02-15 184 views
40

大多數如何調用NSXMLParser的示例都包含在涉及Apps的複雜項目中。演示回調的簡單示例是什麼樣的。NSXMLParser簡單示例

+2

Stack Overflow是,從根本上絕對,一個問題/答案的網站。你可以回答你自己的問題,但你仍然應該遵循這個網站的形式。你的帖子很有用(謝謝!),但它不符合Stack Overflow的意圖。請不要太防守,並根據SO實踐重構您的帖子。 – bkbeachlabs

+1

注意到下次將堅持更多的Q&A風格。至於GitHub,我不知道如何使用它。 – TJA

+0

您能否將解答覆制到下面的答案中,以便我們可以將它解決並從未答覆的列表中解決?謝謝。 –

回答

10

作爲探索NSXMLParser的一部分,我創建了以下非常簡單的代碼。

的main.m

int main(int argc, const char * argv[]) 
{ 

    @autoreleasepool { 
     NSLog(@"Main Started"); 

     NSError *error = nil; 

     // Load the file and check the result 
     NSData *data = [NSData dataWithContentsOfFile:@"/Users/Tim/Documents/MusicXml/Small.xml" 
              options:NSDataReadingUncached 
              error:&error]; 
     if(error) { 
      NSLog(@"Error %@", error); 

      return 1; 
     } 


     // Create a parser and point it at the NSData object containing the file we just loaded 
     NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; 

     // Create an instance of our parser delegate and assign it to the parser 
     MyXmlParserDelegate *parserDelegate = [[MyXmlParserDelegate alloc] init]; 
     [parser setDelegate:parserDelegate]; 

     // Invoke the parser and check the result 
     [parser parse]; 
     error = [parser parserError]; 
     if(error) 
     { 
      NSLog(@"Error %@", error); 

      return 1; 
     } 

     // All done 
     NSLog(@"Main Ended"); 
    } 
    return 0; 
} 

MyXmlParserDelegate.h

#import <Foundation/Foundation.h> 

@interface MyXmlParserDelegate : NSObject <NSXMLParserDelegate> 

@end 

MyXmlParserDelegate.m

#import "MyXmlParserDelegate.h" 

@implementation MyXmlParserDelegate 

- (void) parserDidStartDocument:(NSXMLParser *)parser { 
    NSLog(@"parserDidStartDocument"); 
} 

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { 
    NSLog(@"didStartElement --> %@", elementName); 
} 

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    NSLog(@"foundCharacters --> %@", string); 
} 

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 
    NSLog(@"didEndElement --> %@", elementName); 
} 

- (void) parserDidEndDocument:(NSXMLParser *)parser { 
    NSLog(@"parserDidEndDocument"); 
} 
@end 

我,希望它可以幫助別人的貼吧。

+0

感謝您的出發點。很有幫助。 –

0

以下是以下原始Objective-C代碼的Swift版本。

它是使用XCode 7.3構建和測試的。在寫代理時,我發現從文檔中複製函數原型非常方便。值得注意的是,Swift目前是一個相當迅速移動的目標。

main.swift

import Foundation 

// Let's go 
print("Main: Started") 

// Try to load the file. Display the description of the error if one occurs 
var xmlData : NSData 
do { 
    xmlData = try NSData(contentsOfFile: "/Users/amt/Documents/TestXml/Test.xml", 
         options: .DataReadingMappedIfSafe) 
} 
catch let error as NSError { 
    print("Main: \(error.description)") 

    exit(1) 
} 

// Create a parser and point it at the NSData object containing 
// the file we just loaded 
var parser : NSXMLParser! = NSXMLParser(data: xmlData) 

// Create a parser delegate object and assign it to the parser 
// Beware the "weak" reference and don't try to combine the two lines 
// of code into one unless you like EXC_BAD_ACCESS exceptions 
var parserDelegate : MyXmlParserDelegate = MyXmlParserDelegate() 
parser.delegate = parserDelegate 

// This example also illustrates some of the namespace functions defined in 
// the delegate protocol so enable namespace reporting to see them invoked 
parser.shouldReportNamespacePrefixes = true 

// Parse the document 
if !parser.parse() { 
    // If parse() returned false then an error occurred so display is location 
    // and details 
    let error = parser.parserError 
    let line = parser.lineNumber 
    let col = parser.columnNumber 
    print("Parsing failed at \(line):\(col): \(error?.localizedDescription)") 
} 

// All done 
print("Main: Ended") 
exit(0) 

MyXmlParserDelegate.swift

import Foundation 

class MyXmlParserDelegate:NSObject, NSXMLParserDelegate { 

    @objc func parserDidStartDocument(parser: NSXMLParser) { 
     print("parserDidStartDocument") 
    } 

    @objc func parser(parser: NSXMLParser, didStartElement elementName: String, 
       namespaceURI: String?, qualifiedName qName: String?, 
       attributes attributeDict: [String : String]) { 
     print("didStartElement  --> \(elementName)") 
    } 

    @objc func parser(parser: NSXMLParser, foundCharacters string: String) { 
     print("foundCharacters  --> \(string)") 
    } 

    @objc func parser(parser: NSXMLParser, didEndElement elementName: String, 
       namespaceURI: String?, qualifiedName qName: String?) { 
     print("didEndElement   --> \(elementName)") 
    } 

    @objc func parser(parser: NSXMLParser, didStartMappingPrefix prefix: String, 
       toURI namespaceURI: String) { 
     print("didStartMappingPrefix --> Prefix: \(prefix) toURI: \(namespaceURI)") 
    } 

    @objc func parser(parser: NSXMLParser, didEndMappingPrefix prefix: String) { 
     print("didEndMappingPrefix --> Prefix: \(prefix)") 
    } 

    @objc func parserDidEndDocument(parser: NSXMLParser) { 
     print("parserDidEndDocument") 
    } 
} 
0

夫特4實施例 - 解析XIB-文件。

import Foundation 

class XMLTransformer: NSObject { 

    private let parser: XMLParser 
    private var stack = [Node]() 
    private var tree: Node? 

    init(data: Data) { 
     parser = XMLParser(data: data) 
     super.init() 
     parser.delegate = self 
    } 
} 

extension XMLTransformer { 

    func transform() throws -> Node? { 
     parser.parse() 
     if let e = parser.parserError { 
     throw e 
     } 
     assert(stack.isEmpty) 
     assert(tree != nil) 
     return tree 
    } 

} 

extension XMLTransformer: XMLParserDelegate { 

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { 
     guard let tag = Tag(rawValue: elementName) else { 
     return 
     } 
     let node = Node(tag: tag, attributes: attributeDict, nodes: []) 
     stack.append(node) 
    } 

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { 
     guard let tag = Tag(rawValue: elementName) else { 
     return 
     } 
     let lastElement = stack.removeLast() 
     assert(lastElement.tag == tag) 
     if let last = stack.last { 
     last.nodes += [lastElement] 
     } else { 
     tree = lastElement 
     } 
    } 
} 

extension XMLTransformer { 

    enum Tag: String { 
     case document 
     case objects 
     case tableViewCell, tableViewCellContentView 
     case subviews 
     case mapView 
     case constraints, constraint 
     case connections, outlet 
    } 
} 

extension XMLTransformer { 

    class Node { 

     let tag: Tag 
     let attributes: [String : String] 
     var nodes: [Node] 

     init(tag: Tag, attributes: [String : String], nodes: [Node] = []) { 
     self.tag = tag 
     self.attributes = attributes 
     self.nodes = nodes 
     } 
    } 
} 

用法:

let data = try xib(named: "MapTableViewCell") 
let c = XMLTransformer(data: data) 
let tree = try c.transform() // Here you have parsed XML in a Tree representation.