使用 GDataXML 获取 XML 响应值 [英] Get XML response value with GDataXML
问题描述
在 HTTP Post 之后,我检索到一个 xml 响应,如下所示:
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>
我想提取用户 ID,但我不知道该怎么做.我尝试使用 GDataXML
Parser,因为它已经集成到我的项目中,但是我不知道如何在 html 标签中获取值.
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.
我希望你能帮助我.如果 XMLParser
没有解决方案,你会推荐正则表达式吗?在这种情况下,我会很感激正则表达式的解决方案,我不太擅长这个:)
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 :)
提前致谢.
推荐答案
这是我用来检索用户属性的代码.它有效.
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];
文件 test.xml 与您从 xml 响应中检索到的文件相同.所以你需要改变这段代码的第二行.也许你可以调用 NSData
类的 initWithData
方法.
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
编辑
将这两行放在前面以供说明.
Put these two lines before for instruction.
NSString *valAttribute = [(GDataXMLElement *) [doc.rootElement attributeForName:@"value"] stringValue];
NSLog(@"value attribute for result is %@", valAttribute);
解释很简单.使用 doc.rootElement
可以检索整个 xml 文档,从
到
The explanation is quite simple. With doc.rootElement
you retrieve the entire xml document, from <result>
to </result>
这篇关于使用 GDataXML 获取 XML 响应值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!