0

我只想解析从发布响应收到的字符串,我知道有像 NSXMLParse 这样的库/类,苹果提供了一些示例,但不是我想要的,或者我还没有准备好理解该代码。

我收到这个:

<object>
<id>1</id>
<alias>juan</alias>
<email>jps@sol.pro</email>
</object>
<object>
<id>2</id>
<alias>juana</alias>
<email>jpsa@sol.pro</email>
</object>

然后我需要解析,并得到这样的数据:

NSString *xmlThing = [response];
for xmlThing in-all <object>
{
    uint id = <id>1</id>
    NSString *alias = <alias>juan</alias>
    NSString *email = <email>email@email.com</email>
}

为什么会这样?因为我认为这是处理和解析各种 html、xml 等文件的最简单方法。

我感谢各种帮助。

4

3 回答 3

6

您可以使用 XMLReader 类轻松解析 XML 文件。有关更多详细信息,请查看https://appengineer.in/2013/08/03/xml-parsing-using-xml-reader-in-objective-c/

于 2014-09-06T05:44:21.000 回答
4

您可以使用NSXMLParser及其委托方法。

示例:在 *.h 文件中添加 NSXMLDelegate:

@interface YourClass: NSObject <NSXMLParserDelegate>

*.m 文件:

    @interface YourClass()
    @property NSMutableString *currentXMLValue;
    @property NSMutableArray *objects;
    @end

    @implementation YourClass{
    -(void) processXML {
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData: data];
    self.objects = [[NSMutableArray alloc] init];
    [xmlParser setDelegate: self];
    [xmlParser parse];
    }

    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    {
        //each time part of string is found append it to current string
        [self.currentXMLValue appendString:string];
    }

//here you can check when <object> appears in xml and create this object
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict
{
    //each time new element is found reset string
    self.currentXMLValue = [[NSMutableString alloc] init];
    if( [elementName isEqualToString:@"object"])
    {
        self.obj= [[YourObject alloc] init];
    }
}
//this is triggered when there is closing tag </object>, </alias> and so on. Use it to set object's properties. If you get </object> - add object to array.
    -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    {

        if ([elementName isEqualToString:@"id"]) {
           obj.id = [self.currentXMLValue intValue];
        }
        else if ([elementName isEqualToString:@"alias"]) {
           obj.alias = self.currentXMLValue;
        }
        else if ([elementName isEqualToString:@"object"]) {
        if (self.objects) {
            [self.object addObject:obj];
        }
        }
    //and so on
    } 
    }
于 2013-02-22T15:09:12.610 回答
0

好吧,上面的答案似乎很完美,但是如果您有大量数据和更快的处理速度,我建议您使用其他解析器,您可以在这里使用 TBXML、xml 比较

于 2013-02-22T18:02:46.323 回答