12

由于 NSXML 在实际 iPhone 上的给定限制,我正在使用 TouchXml。无论如何,我刚刚开始使用 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];

基本上节点评估为零

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

更新 1:我已经放弃使用 XPath 进行解析,并将其替换为 NSURLRequest,所以现在我将整个 XML 放在一个字符串中,但我对 Objective-C 的粗鲁介绍仍在继续……我刚刚意识到我对.NET BCL,Regex 之类的东西很容易获得。

UPDATE2:我已经弄清楚如何使用 RegexKitLite 进行正则表达式。

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

4

3 回答 3

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];
于 2009-02-09T01:52:37.370 回答
0

我有一个类似的问题。对指定了命名空间 (xmlns="http://somenamespace") 的 XML 进行任何选择都将导致找不到节点。考虑到它确实支持额外的命名空间格式,例如 xmlns:somenamespace="http://somenamespace",这很奇怪。

在任何情况下,到目前为止,最简单的做法是进行字符串替换并将 xmlns="http://tempuri.org/webservices 替换为空字符串。

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

于 2009-07-15T23:46:34.337 回答
-1

尝试

NSArray *nodes = [myParser nodesForXPath:@"/FundInfo/*" error:&err];
于 2009-02-09T01:50:11.730 回答