2012-07-25 87 views
0

我得到了一些對XML的支持,形成一個Web服務:從iOS中提取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。有沒有一個很好的和簡單的方法來做到這一點在iOS?

+0

有解析XML文件的開源框架。但是,像這樣的簡單結構可以使用NSDictionary dictionaryWithContentOfFile讀取。在這種情況下,你會收到一本字典。它有一個對象。該對象是一個存儲在「NewDataSet」鍵中的字典。這包含了與「表」的關鍵字的一個詞。那是一個詞典,它也存儲你的值與關鍵城市,州,郵政編碼,AREA_CODE和TIME_ZONE。 – 2012-07-25 11:11:13

+0

嚴格來說,讀取的文件必須是屬性列表。屬性列表恰巧也是XML。有關它的更多信息,請參閱https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html。它應該適合你的情況,是一個非常簡單的實現。對於更復雜的XML,這可能無法正常工作。它也可能不適用於非常大的XML文件,因爲該文件的內容完全存儲在一個Dictionary對象中。 – 2012-07-25 11:14:03

回答

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"]); 

} 
+0

我看了這個,我的項目是使用ARC – Slee 2012-07-25 11:15:27

+0

爲那些項目文件禁用arc.http://stackoverflow.com/questions/6646052/how-can-i-disable-arc-for-a-single-file- IN-A-項目 – 2012-07-25 11:27:07

0

有丟失的工具來完成這項工作(link)。我建議使用SAX方法,因爲您只需解析此XML數據(例如NSXMLParser)。

0

請看:NSXMLParser

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

它的使用非常簡單。 `

0

可以使用的NSXMLParser,我在我的Mac是不是現在這樣的大炮仔細檢查,但基本上你設置一個的NSXMLParser與返回的數據。然後,您將一個類設置爲解析器的委託,當解析器碰到一個元素時,它會告訴您它已經命中的元素,它是屬性。

如果您對Web服務有任何控制權,我會認真考慮使用JSON數據而不是XML。 ObjC帶有一個非常好的JSON解析器。

1

使用xmldocument parser使用NSXMLParser編寫,但使用開發人員可以使用的更簡單的函數。

  1. 添加SMXMLDocument.h和.m文件到您的項目
  2. 添加#進口在類實現文件(.m文件)

    // 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 
    } 
    

附:我沒有運行這個代碼,但修改了基於類似用法的情況。