2012-02-03 148 views
0

我有一個xml文件,我可以使用NSXML解析器進行解析。現在我想開始解析特定的標記,這可以做到這一點?如何從特定標記解析xml

<RootElement> 
<City> 
<Name>WC</Name> 
<Time>6 am</Time> 
<Notes>Hi</Notes> 
</City> 
    <State> 
    <Name>ABC</Name> 
    <Time>6 a.m.</Time> 
    <Time>2 a.m.</Time> 
    <Notes>This is a note for ABC</Notes> 
    </State> 
    <State> 
    <Name>DEF</Name> 
    <Time>8 am</Time> 
    <Time>10 am</Time> 
    <Notes>This is a note for DEF</Notes> 
    </State> 
</RootElement> 

現在解析應該從國家的標籤開始,但它解析整個文檔並顯示姓名,時間,距離城市標籤還指出。從指定的標籤解析,它是如何完成的?

回答

1

看看:

- (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error 

編輯:代碼示例

NSError* error; 

CXMLDocument *doc = [[CXMLDocument alloc] initWithData:Data options:0 error:&error]; 

// figure out what nodes are in the doc, and pick it apart with the nodesForXPath call 
NSArray * results = [doc nodesForXPath:@"/RootElement" error:&error]; 
NSString * finalUrl = self.defaultURL; 

if ([results count] > 0) { 
    NSString * element = [(CXMLElement *)[results objectAtIndex:0] stringValue]; 
    if ([element isEqualToString:@"State") { 
     // Do state processing 
    } 
} 
[doc release]; 
+0

有點困惑,我是新手,請告訴我,我怎樣才能使用,在didStartElement? – Cyril 2012-02-03 04:47:21

+0

我添加了一些示例代碼。也看看這篇文章:http://stackoverflow.com/questions/8055817/nsxmldocument-search-with-nodesforxpath – Rayfleck 2012-02-03 23:09:51