tes*_*dtv 10 iphone objective-c nsxmlparser
我有这样的XML
<IS>
<Value>
<Signature>-804</Signature>
<Amount>139</Amount>
</Value>
<Value>
<Signature>-845</Signature>
<Amount>639466</Amount>
</Value>
<Value>
<Signature>-811</Signature>
<Amount>16438344</Amount>
</Value>
<Value>
<Signature>-1115</Signature>
<Amount>-159733</Amount>
</Value>
</IS>
Run Code Online (Sandbox Code Playgroud)
现在我想从中解析特定的值.例如,如何将具有相应签名的节点的值作为-804
请帮我..
我知道NSXMLParser的基础知识,但不知道如何实现条件解析.
谢谢.
Asa*_*han 10
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentKey = nil;
[currentStringValue release];
currentStringValue = nil;
if([elementName isEqualToString:@"Value"]){
//alloc some object to parse value into
} else if([elementName isEqualToString:@"Signature"]){
currentKey = @"Signature";
return;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(currentKey){
if(!currentStringValue){
currentStringValue = [[NSMutableString alloc] initWithCapacity:200];
}
[currentStringValue appendString:string];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:@"Signature"] && [currentStringValue intValue] == 804){
ivar.signature = [currentStringValue intValue];
return;
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西.注意我还没有在编译器上测试过这段代码,因此会出现语法错误.
您可能希望使用TouchXML - https://github.com/mrevilme/TouchXML,它提供了一些很好的XML处理功能,包括使用XPATH,这使得您尝试做的更简单.
基于您的模型的假设示例:
//first, load an XML document
CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithXMLString:someXMLString options:0 error:&error];
//get node
CXMLNode *amountNode = [xmlDoc nodeForXPath:@"//Value[@Signature='-804']/Amount" error:&error];
//or get actual value of node
NSSString *amountString = = [[xmlDoc nodeForXPath:@"//Value[@Signature='-804']/Amount" error:&error] stringValue];
Run Code Online (Sandbox Code Playgroud)
注意:这些exapmles都没有经过测试.
我发现TouchXML非常实用且紧凑.
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
42385 次 |
| 最近记录: |