Get XML response value with GDataXML

落花浮王杯 提交于 2020-01-15 04:00:12

问题


after a HTTP Post I retrieve an xml response like the following:

<result value="OK">
    <user id="1">
            <name>admin</name>
            <rank>0</rank>
            <picture_count>0</picture_count>
            <comment_count>0</comment_count>
            <has_profile>1</has_profile>
    </user>
</result>

I'd like to extract the user ID, but I don't know how to do this. I tried with GDataXML Parser, because this is already integrated in my project, but I don't know how to get a value inside a html tag.

I hope you can help me. If there is no solution with XMLParser, would you recommend regular expressions? In this case, I would appreciate a solution for the regex expression, I'm not very good at this :)

Thanks in advance.


回答1:


This is the code I use to retrieve the user attribute. It works.

NSString* path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"xml"];

NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData 
                                                           options:0 error:&error];

NSArray *userElements = [doc.rootElement elementsForName:@"user"];

for (GDataXMLElement *userEl in userElements) {

    // Attribute
    NSString *attribute = [(GDataXMLElement *) [userEl attributeForName:@"id"] stringValue];        
    NSLog(@"attribute for user is %@", attribute);

    // Name
    NSArray *names = [userEl elementsForName:@"name"];
    if (names.count > 0) {
        GDataXMLElement *name = (GDataXMLElement *) [names objectAtIndex:0];

        NSLog(@"name for user is %@", name.stringValue);
    }

    // Rank
    NSArray *ranks = [userEl elementsForName:@"rank"];
    if (ranks.count > 0) {
        GDataXMLElement *rank = (GDataXMLElement *) [ranks objectAtIndex:0];

        NSLog(@"rank for user is %@", rank.stringValue);
    }

    // Do the same for other tags...     
}

[doc release];
[xmlData release];

The file test.xml is the same that you retrieve from the xml response. So you need to change the second line of this snippet of code. Maybe you can call initWithData method of class NSData.

You can put this code where you want. Maybe you can create an other class that works as a centralized parser. Hope it helps

EDIT

Put these two lines before for instruction.

NSString *valAttribute = [(GDataXMLElement *) [doc.rootElement attributeForName:@"value"] stringValue];        
NSLog(@"value attribute for result is %@", valAttribute);

The explanation is quite simple. With doc.rootElement you retrieve the entire xml document, from <result> to </result>



来源:https://stackoverflow.com/questions/8741698/get-xml-response-value-with-gdataxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!