从iOS中的XML中提取值?

时间:2012-07-25 11:04:15

标签: objective-c ios xml

我从Web服务中获取了一些XML:

<?xml version="1.0" encoding="utf-8"?>
<NewDataSet>
  <Table>
    <CITY>Jupiter</CITY>
    <STATE>FL</STATE>
    <ZIP>33477</ZIP>
    <AREA_CODE>561</AREA_CODE>
    <TIME_ZONE>E</TIME_ZONE>
  </Table>
</NewDataSet>

我需要一种简单干净的方法来获取此XML的CITY和STATE值。在iOS中有这么好的简单方法吗?

5 个答案:

答案 0 :(得分:2)

Theres是一个整洁的NSXMLParser Wrapper,可以为您将XML文件转换为NSDictionary。

简单干净!

http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/

然后从那里,您可以使用:

NSDictionary *dict = [self convertXML:xmlContents];
NSArray *tables = [dict objectForKey:@"NewDataSet"];

for (NSDictionary *table in tables) {

   NSLog(@"City = %@", [table objectForKey:@"city"]);

}

答案 1 :(得分:1)

使用使用NSXMLParser编写的xmldocument parser,但开发人员可以使用更简单的函数。

  1. 将SMXMLDocument.h和.m文件添加到项目中
  2. 在类实现文件(.m文件)中添加#import

    // create a new SMXMLDocument with the contents the xml file
    // data is the NSData representation of your XML
    SMXMLDocument *document = [SMXMLDocument documentWithData:data error:&error];
    
    // Pull out the <NewDataSet> node
    SMXMLElement *dataset = [document.root childNamed:@"NewDataSet"];
    
    // Look through <Table> children
    for (SMXMLElement *table in [dataset childrenNamed:@"Table"]) {
        // demonstrate common cases of extracting XML data
        NSString *city = [table valueWithPath:@"CITY"]; // child node value
        NSString *state = [table valueWithPath:@"STATE"]; // child node value
    }
    
  3. P.S。我没有运行此代码,但根据类似的用法进行了修改以匹配您的案例。

答案 2 :(得分:0)

完成这项任务的工具已经丢失(link)。我建议使用SAX方法,因为您只需解析此XML数据(例如NSXMLParser)。

答案 3 :(得分:0)

请查看:NSXMLParser

和方法:(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

使用起来非常简单。 `

答案 4 :(得分:0)

你可以使用NSXMLParser,我现在不在我的Mac上,所以cannon双重检查,但基本上你设置了一个NSXMLParser与回来的数据。然后,您将一个类设置为解析器的委托,当解析器命中一个元素时,它将告诉您它击中了哪个元素及其属性。

如果您对Web服务有任何控制权,我会认真考虑使用JSON数据而不是XML。 ObjC带有一个非常好的JSON解析器。