Cocoa Touch/iPhone 中的 XML 解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/773651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:27:40  来源:igfitidea点击:

XML Parsing in Cocoa Touch/iPhone

iphonexmlcocoa-touch

提问by Shoaibi

Okay i have seen TouchXML, parseXML, NSXMLDocument, NSXMLParser but i am really confused with what to to do.

好吧,我已经看过 TouchXML、parseXML、NSXMLDocument、NSXMLParser,但我真的很困惑该怎么做。

I have an iphone app which connects to a servers, requests data and gets XML response. Sample xml response to different set of queries is give at http://pastebin.com/f681c4b04

我有一个 iphone 应用程序,它连接到服务器,请求数据并获得 XML 响应。http://pastebin.com/f681c4b04给出了对不同查询集的示例 xml 响应

I have another classes which acts as Controller (As in MVC, to do the logic of fetch the data). This class gets the input from the View classes and processes it e.g. send a request to the webserver, gets xml, parses xml, populates its variables (its a singleton/shared Classes), and then responses as true or false to the caller. Caller, based on response given by the controller class, checks controller's variables and shows appropriate contents to the user.

我有另一个充当控制器的类(如在 MVC 中,执行获取数据的逻辑)。这个类从 View 类获取输入并处理它,例如向 Web 服务器发送请求,获取 xml,解析 xml,填充其变量(它的单例/共享类),然后向调用者响应 true 或 false。调用者根据控制器类给出的响应,检查控制器的变量并向用户显示适当的内容。

I have the following Controller Class variables:

我有以下控制器类变量:

@interface backendController : NSObject {
NSMutableDictionary *searchResults, *plantInfoResults, *bookmarkList, *userLoginResult;
}

and functions like getBookmarkList, getPlantInfo. Right now i am printing plain XML return by the webserver by NSLog(@"Result: :%@" [NSString stringWithContentsOfURL:url])

以及 getBookmarkList、getPlantInfo 等函数。现在我正在打印由网络服务器通过 NSLog(@"Result: :%@" [NSString stringWithContentsOfURL:url]) 返回的纯 XML

I want a generic function which gets the XML returned from the server, parseses it, makes a NSMutableDictionary of it containing XML opening tags' text representation as Keys and XML Tag Values as Values and return that.

我想要一个通用函数,它获取从服务器返回的 XML,解析它,制作一个 NSMutableDictionary,它包含 XML 开始标记的文本表示作为键和 XML 标记值作为值并返回。

Only one question, how to do that?.

只有一个问题,如何做到这一点?

采纳答案by Sean

Have you tried any of the XML Parsers you mentioned? This is how they set the key value of a node name:

您是否尝试过您提到的任何 XML 解析器?这是他们如何设置节点名称的键值:

[aBook setValue:currentElementValue forKey:elementName];

P.S. Double check your XML though, seems you are missing a root node on some of your results. Unless you left it out for simplicity.

PS 但是,请仔细检查您的 XML,似乎您在某些结果中缺少根节点。除非你为了简单而把它省略了。

Take a look at w3schools XML tutorial, it should point you in the right direction for XML syntax.

看看w3schools XML 教程,它应该为您指明 XML 语法的正确方向。

回答by Alex Reynolds

Consider the following code snippet, that uses libxml2, Matt Gallagher's libxml2 wrappersand Ben Copsey's ASIHTTPRequestto parse an HTTP document.

考虑以下代码片段,它使用libxml2Matt Gallagher 的 libxml2 包装器Ben Copsey 的 ASIHTTPRequest来解析 HTTP 文档。

To parse XML, use PerformXMLXPathQueryinstead of the PerformHTTPXPathQueryI use in my example.

要解析 XML,请使用PerformXMLXPathQuery而不是PerformHTTPXPathQuery我在示例中使用的 。

The nodesinstance of type NSArray *will contain NSDictionary *objects that you can parse recursively to get the data you want.

nodes类型的实例NSArray *将包含NSDictionary *您可以递归解析以获取所需数据的对象。

Or, if you know the scheme of your XML document, you can write an XPath query to get you to a nodeContentor nodeAttributevalue directly.

或者,如果您知道 XML 文档的方案,则可以编写 XPath 查询以直接获取 anodeContentnodeAttribute值。

ASIHTTPRequest *request = [ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://stackoverflow.com/"];
[request start];
NSError *error = [request error];
if (!error) {
    NSData *response = [request responseData];
    NSLog(@"Root node: %@", [[self query:@"//" withResponse:response] description]);
}
else 
    @throw [NSException exceptionWithName:@"kHTTPRequestFailed" reason:@"Request failed!" userInfo:nil];
[request release];

...

- (id) query:(NSString *)xpathQuery withResponse:(NSData *)respData {
    NSArray *nodes = PerformHTMLXPathQuery(respData, xpathQuery);
    if (nodes != nil)
        return nodes;
    return nil;
}

回答by Ravi_Parmar

providing you one simple example of parsing XML in Table, Hope it would help you.

为您提供一个解析表中 XML 的简单示例,希望对您有所帮助。

//XMLViewController.h

//XMLViewController.h

#import <UIKit/UIKit.h>
@interface TestXMLViewController : UIViewController<NSXMLParserDelegate,UITableViewDelegate,UITableViewDataSource>{
@private
NSXMLParser *xmlParser;
NSInteger depth;
NSMutableString *currentName;
NSString *currentElement;
NSMutableArray *data;
}
@property (nonatomic, strong) IBOutlet UITableView *tableView;
-(void)start;
@end

//TestXMLViewController.m

//TestXMLViewController.m

#import "TestXmlDetail.h"
#import "TestXMLViewController.h"
@interface TestXMLViewController ()
- (void)showCurrentDepth;

@end

@implementation TestXMLViewController

@synthesize tableView;
- (void)start
{
NSString *xml = @"<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Node><name>Main</name><Node><name>first row</name></Node><Node><name>second row</name></Node><Node><name>third row</name></Node></Node>";
xmlParser = [[NSXMLParser alloc] initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
[xmlParser setDelegate:self];
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:NO];
[xmlParser parse];

}


- (void)parserDidStartDocument:(NSXMLParser *)parser 
{
NSLog(@"Document started");
depth = 0;
currentElement = nil;
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError 
{
NSLog(@"Error: %@", [parseError localizedDescription]);
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName 
attributes:(NSDictionary *)attributeDict
{

currentElement = [elementName copy];

if ([currentElement isEqualToString:@"Node"])
{
    ++depth;
    [self showCurrentDepth];
}
else if ([currentElement isEqualToString:@"name"])
{

    currentName = [[NSMutableString alloc] init];
}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName
{

if ([elementName isEqualToString:@"Node"]) 
{
    --depth;
    [self showCurrentDepth];
}
else if ([elementName isEqualToString:@"name"])
{
    if (depth == 1)
    {
        NSLog(@"Outer name tag: %@", currentName);
    }
    else 
    {
        NSLog(@"Inner name tag: %@", currentName);
      [data addObject:currentName];
    }
    }
   }        

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([currentElement isEqualToString:@"name"]) 
{
    [currentName appendString:string];
} 
}

- (void)parserDidEndDocument:(NSXMLParser *)parser 
{
    NSLog(@"Document finished", nil);
}



- (void)showCurrentDepth
{
  NSLog(@"Current depth: %d", depth);
}


- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
 data = [[NSMutableArray alloc]init ];
[self start];
self.title=@"XML parsing";
NSLog(@"string is %@",data);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
`enter code here`return [data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [data objectAtIndex:indexPath.row];
return cell;
}
@end