我将XML数据解析如下,它在objective-C中工作(如果需要,我可以显示objective-C代码)。

//Update

//NSData
    response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://kalkatawi.com/jsonTest.php"]];

if(response!=nil) {

NSError *parseError = nil;

jsonArray1 = [[NSMutableArray alloc] init];

for(int i=0;i<[jsonArray count];i++)
{
    NSString  * city = [[jsonArray objectAtIndex:i] objectForKey:@"city"];

    [jsonArray1 addObject:city];

    NSLog(@"%@", jsonArray1);
}

我的网络结果:
<city>1</city><city>2</city><city>3</city>

我读过这个关于How to parse a JSON file in swift?的主题,但是我在"fatal error: unexpectedly found nil while unwrapping an Optional value"行中遇到了一个jsonData问题。那么,我的问题在哪里呢?
我的代码:
    let urlPath = "http://example.net/example/example.php"

    //Crash happens here
    let jsonData: NSData = NSData.dataWithContentsOfFile(urlPath, options: .DataReadingMappedIfSafe, error: nil)

    let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

    for parseData in jsonDict {

        println(parseData)
    }

最佳答案

编辑:看起来苹果还没有在Swift中实现NSXMLDocument。这里有一个库可以帮助您在Swift中解析XML:https://github.com/ndavidsson/NDHpple
如果它被实现了,这就是你要做的:

let urlPath:NSURL = NSURL(scheme:"http", host:"example.net", path:"example/example.php")
var error: NSErrorPointer? = nil
var xml:NSXMLDocument = NSXMLDocument(contentsOfUrl: urlPath, error: error!)

此时,xml将表示NSXMLDocument。
https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSXMLDocument_Class/

10-07 19:05
查看更多