大家下午好,
我已经从 Web 服务下载了数据,我希望解析该数据以便我可以使用它,但是我在解析返回值时遇到问题,下面是获取代码以及介于两者之间的任何其他帮助赞赏
-(IBAction)runNewImport:(id)sender{
recordResults = FALSE;
soapMessage = [NSString stringWithFormat:
@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<s:Envelope \n"
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n"
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n"
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"> \n"
"<s:Body> \n"
"<[FUNCTION] xmlns=\"http://tempuri.org/\"/>\n"
"</s:Body> \n"
"</s:Envelope>"];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSURL *url = [NSURL URLWithString:@"http://[PATH]"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"[FUNCTION]" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
webData = [NSMutableData data];
NSLog(@"%@",webData);
}
else {
NSLog(@"theConnection is NULL");
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(@"THIS IS THE DATA : %@",theXML);
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)
elementName namespaceURI:(NSString *)
namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if( [elementName isEqualToString:@"CODE"])
{
soapResults = [[NSMutableString alloc] init];
NSLog(@"%@",soapResults);
recordResults = TRUE;
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)
elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if( [elementName isEqualToString:@"CODE"])
{
recordResults = FALSE;
soapResults = nil;
}
}
感谢您的再次光临,欢迎大家的帮助
最佳答案
您似乎误解了 NSXMLParser 的工作方式。我强烈建议您仔细阅读 Apple 的这份文档 XML parsing
-(void)parser:didStartElement:namespaceURI:qualifiedName:attributes:
当解析器发现像 的开始 XML 标记时调用此方法,因此它上面还没有任何数据。在这里,你只需要为你想保存的东西分配内存
- (void)parser:foundCharacters:
当在 parser:didStartElement:namespaceURI:qualifiedName:attributes: 中找到的标记内有数据时调用在下一个方法中你想要的对象:
-(void)parser:didEndElement:namespaceURI:qualifiedName
在解析器遇到结束标记 () 时调用。现在您已将数据保存在 parser:foundCharacters: 中的变量中,是时候将其保存在您的对象中了。
编辑:好的,让我们尝试通过在这些方法中添加代码示例来分解它:
假设您有一个如下所示的 XML;
<person>
<lastName>Doe</lastName>
<firstName>John</firstName>
<address>
<street>100 Main Street</street>
<city>Somewhere</city>
</address>
</person>
自然地,您希望拥有一个具有属性 lastName、firstName 和 addressDictionary 的 Person 类包含街道 和城市。要保留所有 Person,您需要 personArray。
现在我们有了结构,下面是解析部分。 请注意,为了更好地理解,我将分别编写每个 If block 。
.h文件
@property (nonatomic, retain) Person *currentPerson;
@property (nonatomic, retain) NSMutableString *currentElement;
@property (nonatomic, retain) NSMutableDictionary *addressDic; //to be saved to person.addressDictionary when finished
@property (nonatomic, retain) NSMutableArray *personArray;
.m文件
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
personArray = [[NSMutableArray alloc] init];
}
- (void) parser: (NSXMLParser *) parser didStartElement: (NSString *) elementName
namespaceURI: (NSString *) namespaceURI qualifiedName: (NSString *) qName attributes: (NSDictionary *) attributeDict
{
if ([elementName isEqualToString:@"Person"])
{
currentPerson = [[Person alloc] init]; //
return;
}
if ([elementName isEqualToString:@"lastName"])
{
currentElement = [[NSMutableString alloc] init];
return;
}
if ([elementName isEqualToString:@"firstName"])
{
currentElement = [[NSMutableString alloc] init];
return;
}
if ([elementName isEqualToString:@"address"])
{
adressDic = [[NSMutableDictionary alloc] init];
return;
}
if ([elementName isEqualToString:@"street"])
{
currentElement = [[NSMutableString alloc] init];
return;
}
if ([elementName isEqualToString:@"city"])
{
currentElement = [[NSMutableString alloc] init];
return;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[currentElement appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"Person"])
{
[personArray addObject:currentPerson];
[currentPerson release];
return;
}
if ([elementName isEqualToString:@"lastName"])
{
currentPerson.lastName = currentElement;
[currentElement release]; currentElement = nil;
return;
}
if ([elementName isEqualToString:@"firstName"])
{
currentPerson.firstName = currentElement;
[currentElement release]; currentElement = nil;
return;
}
if ([elementName isEqualToString:@"address"])
{
currentPerson.addressDictionary = addresDic;
[addressDic release];
return;
}
if ([elementName isEqualToString:@"street"])
{
[addressDic setObject:currentElement forKey:@"street"];
[currentElement release]; currentElement = nil;
return;
}
if ([elementName isEqualToString:@"city"])
{
[addressDic setObject:currentElement forKey:@"city"];
[currentElement release]; currentElement = nil;
return;
}
}
当这一切都完成后,parserDidEndDocument: 被调用。现在你的数组中有了所有的 Person,你可以对它们做任何你想做的事
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
for (Person *person in personArray)
{
NSLog(@"Person name:%@", person.firstName);
NSLog(@"Person lastname:%@", person.lastName);
}
}
关于objective-c - 解析 Webservice 数据 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11139551/
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und