如何通过解析XML文件来检索值

时间:2014-11-24 16:42:04

标签: ios xcode parsing

我试图从XML文件中收集数据并添加到数组中。数据看起来像这样..

<Placemark>
<name><![CDATA[Kingsway (Start)]]></name>
<description><![CDATA[]]></description>
<TimeStamp><when>2014-04-30T17:03:28.681Z</when></TimeStamp>
<styleUrl>#start</styleUrl>
<Point>
<coordinates>-1.408894,52.13977,176.0</coordinates>
</Point>
</Placemark>
<Placemark id="tour">
<name><![CDATA[Kingsway]]></name>
<description><![CDATA[]]></description>
<styleUrl>#track</styleUrl>
<ExtendedData>
<Data name="type"><value><![CDATA[running]]></value></Data>
</ExtendedData>
<gx:MultiTrack>
<altitudeMode>absolute</altitudeMode>
<gx:interpolate>1</gx:interpolate>
<gx:Track>
<when>2014-04-30T17:03:28.681Z</when>
<gx:coord>-1.408894 52.13977 176.0</gx:coord>
<when>2014-04-30T17:03:31.071Z</when>
<gx:coord>-1.407839 52.139166 174.0</gx:coord>
<when>2014-04-30T17:03:32.070Z</when>
<gx:coord>-1.407486 52.138963 175.0</gx:coord>
<when>2014-04-30T17:03:33.073Z</when>
<gx:coord>-1.407142 52.138755 174.0</gx:coord>
<when>2014-04-30T17:03:34.073Z</when>
<gx:coord>-1.406805 52.138555 173.0</gx:coord>
<when>2014-04-30T17:03:35.073Z</when>
<gx:coord>-1.40663 52.138441 173.0</gx:coord>
<when>2014-04-30T17:03:36.601Z</when>
<gx:coord>-1.405929 52.138027 172.0</gx:coord>
<when>2014-04-30T17:03:37.601Z</when>
<gx:coord>-1.405574 52.137817 172.0</gx:coord>

我只对标签gx:coord后面的值感兴趣,所以我使用下面的代码解析文件。

- (void)loadMap:(NSInteger)selJourney
{
    NSString *journey = @"KML_Sample";
    NSString *path = [[NSBundle mainBundle] pathForResource:journey ofType:@"kml"];
    [self parseXMLFile:path];
}

- (void)parseXMLFile:(NSString *)pathToFile
{
    NSXMLParser *addressParser;

    [myParser setShouldProcessNamespaces:NO];
    [myParser setShouldReportNamespacePrefixes:NO];
    [myParser setShouldResolveExternalEntities:NO];

    NSURL *xmlURL = [NSURL fileURLWithPath:pathToFile];
    myParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    [myParser setDelegate:self];
    [myParser setShouldResolveExternalEntities:YES];
    [myParser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:   (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ( [elementName isEqualToString:@"gx:coord"] ) {
        polylineList = [[NSMutableArray alloc] init];
    }
}

当解析器方法运行并找到正确的elementName时,我想在标记之后检索字符串数据并将其添加到我的NSMutableArray polylineList。 解析器中的其他参数都返回nil,所以我错过了什么?

1 个答案:

答案 0 :(得分:0)

我设法使用下面的方法解决了这个问题

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ((addRec) && (![string isEqualToString:@"\n"]))
    {
        NSArray *tmpArray = [[NSArray alloc] initWithObjects:string, nil];
        if (polylineList.count > 0)
            [polylineList addObject:string];
        else
            polylineList = [[NSMutableArray alloc] initWithArray:tmpArray];
    }
}

我希望这对使用KML,MapKit或只解析XML的人有所帮助。