2013-12-19 95 views
0

我有多個入口節點的XML文件:解析使用GDataXML與XPATH

<entry> 
    <published>2013-12-19T13:30:20-05:00</published> 
    <title>This is a title</title> 
    <content type="html">This is the content</content> 
    <author> 
     <name>Valentina</name> 
    </author> 
</entry> 

我想使用它的XPath(用於學習目的),但我似乎無法使它工作進行解析。我有以下代碼:

 NSData* xmlData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:link]]; 
     GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil]; 

     NSArray* entries = [document.rootElement elementsForName:@"entry"]; 
     for(GDataXMLElement* element in entries) 
     { 
      published = [element nodesForXPath:@"/entry/published" error:nil][0]; 
     } 

試圖讓published節點文本時,我總是index 0 beyond bounds for empty array得到一個錯誤。我嘗試了不同的東西,但無法弄清楚什麼是正確的方式。
條目數組包含10個條目節點。

回答

1

XPath根據當前上下文進行評估,該上下文已經是<entry/>元素。將XPath表達式更改爲./published甚至只是published

published = [element nodesForXPath:@"published" error:nil][0]; 

但是,如果你只是想查詢一個子節點,爲什麼要使用XPath呢?

published = [element elementsForName:@"published"][0];