2009-02-09 56 views
12

由於在實際的iPhone上給定了NSXML的限制,因此我使用了TouchXml。無論如何,我剛剛開始接觸的Objective-C,我來自一個C#背景,感覺就像學習的東西new..anyhow ..這裏是我的xml文件...使用TouchXML獲取可可元素的值

<?xml version="1.0" encoding="utf-8"?> 
<FundInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/webservices"> 
    <FundsReleaseDate>2009-02-11T00:00:00</FundsReleaseDate> 
    <FundValue>7800</FundValue> 
    <FundShares>1000</FundShares> 
</FundInfo> 

我想獲得7800,即FundValue。有人點我在正確的方向,我現在用的是TouchXml CXMLDocument和myParser的類型是CXMLDocument的,我已經試過

NSArray *nodes = [myParser nodesForXPath:@"//FundInfo" error:&err]; 

基本上節點的計算結果爲無

if ([nodes count] > 0) { 
    amount = [nodes objectAtIndex:1]; 
} 

更新1:我已經放棄使用XPath解析,並用NSURLRequest取代它,所以現在我有一個字符串中的整個XML,但我對粗略的Objective-C介紹繼續...我剛纔意識到我已經變成了.NET BCL,正則表達式非常容易獲得。

UPDATE2:我已經想出瞭如何使用RegexKitLite for regex。

所以現在的問題是,我如何從FundValue裏面得到「7800」,現在它是一個大字符串。我已經通過使用NSLog寫入它來證實我在我的NSString中有它。

回答

25

的問題是,你的XML有一個命名空間,這意味着你的XPath實際上並不匹配。不幸的是,沒有默認映射,並且XPath實際上並沒有定義一個好的內部處理方法,因此您無法通過更改XPath來修復它。相反,您需要通知解釋器如何將其映射到您的XPath中。

看起來TouchXML實現通過這種支持:

- (NSArray *)nodesForXPath:(NSString *)xpath namespaceMappings:(NSDictionary *)inNamespaceMappings error:(NSError **)error; 

所以你可以嘗試這樣的:

NSDictionary *mappings = [NSDictionary dictionaryWithObject:@"http://tempuri.org/webservices" forKey:@"tempuri"]; 
[myParser nodesForXPath:@"//tempuri:FundInfo" namespaceMappings:mappings error:&err]; 
+0

感謝您的答覆,我得到一個崩潰有以下異常消息:。 [CXMLElement isEqualToString :]:發送到實例的無法識別的選擇器 – kd7 2009-02-09 03:33:32

-1

嘗試

NSArray *nodes = [myParser nodesForXPath:@"/FundInfo/*" error:&err]; 
+0

如上的回答說,你所需要的'namespaceMapping` – 2010-07-22 17:15:47

0

我有一個類似的問題。對具有指定名稱空間的XML(xmlns =「http:// somenamespace」)的任何選擇都將導致找不到節點。很奇怪,考慮到它支持額外的命名空間格式,如xmlns:somenamespace =「http:// somenamespace」。

在任何情況下,通過做的是最簡單的事的字符串替換,並用空字符串替換的xmlns =「http://tempuri.org/webservices。

總的來說我喜歡touchxml,但我不能相信這個漏洞仍然存在