代码之家  ›  专栏  ›  技术社区  ›  Ta01

使用TouchXML获取Cocoa中元素的值

  •  12
  • Ta01  · 技术社区  · 16 年前

    我使用TouchXml是因为NSXML在实际iPhone上的限制。不管怎样,我刚开始学习Objective-C,我有C#背景,我想学习一些新东西。不管怎样,这是我的xml文件。..

    <?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];
    

    基本上,节点的计算结果为nil

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

    更新1:我已经放弃了使用XPath进行解析,并将其替换为NSURLRequest,因此现在我将整个XML保存在一个字符串中,但我对objective-C的粗鲁介绍仍在继续。..我刚刚意识到我已经被宠坏了。NET BCL,像Regex这样的东西很容易获得。

    更新2:我已经弄清楚了如何将RegexKitLite用于正则表达式。

    所以现在的问题是,我如何从FundValue内部获取“7800”,它现在是一个大字符串。我已经通过使用NSLog编写它来确认我的NSString中有它。

    3 回复  |  直到 16 年前
        1
  •  25
  •   Louis Gerbarg    16 年前

    问题是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];
    
        2
  •  0
  •   michael michael    16 年前

    我也有类似的问题。指定了命名空间的XML上的任何选择(xmlns=“http://somenamespace“)将导致找不到节点。考虑到它确实支持其他命名空间格式,如xmlns:somenamespace=,这很奇怪。”http://somenamespace".

    无论如何,通过 远的 最简单的方法是执行字符串替换,并替换xmlns=“http://tempuri.org/webservices一个空字符串。

    总的来说,我喜欢touchxml,但我不敢相信这个bug仍然存在。

        3
  •  -1
  •   Adam Rosenfield    16 年前

    尝试

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