技术的乐趣在于分享,欢迎多多交流,多多沟通。
全部博文(877)
分类: iOS平台
2015-10-19 20:11:25
//创建根节点
GDataXMLElement *rootElement = [GDataXMLNode elementWithName:@"abCASD"];
//创建第一个子节点
GDataXMLElement *element = [GDataXMLNode elementWithName:@"name123" stringValue:@"东方红"];
//添加子节点到根节点上
[rootElement addChild: element];
//使用根节点创建xml文档
GDataXMLDocument *rootDoc = [[GDataXMLDocument alloc] initWithRootElement:rootElement];
//设置使用的xml版本号
[rootDoc setVersion:@"1.0"];
//设置xml文档的字符编码
[rootDoc setCharacterEncoding:@"utf-8"];
//获取并打印xml字符串
NSString *str = [[NSString alloc] initWithData:rootDoc.XMLData encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
//解析XML
GDataXMLElement *root = [rootDoc rootElement];
for (int i=0; i <[rootElement childCount]; i++) {
//GDataXMLElement *element = (GDataXMLElement *)[root childAtIndex:i];
NSLog(@"ROOT Element Name = %@", root.name);
NSLog(@"ROOT Type = %@", [[root attributeForName:@"type"] stringValue]);
GDataXMLElement *element = (GDataXMLElement *)[root childAtIndex:i];
NSLog(@"Element Name = %@", element.name);
NSLog(@"Type = %@", [[element attributeForName:@"type"] stringValue]);
for (int j=0; j<[element childCount]; j++) {
GDataXMLElement *subItem = (GDataXMLElement *)[element childAtIndex:j];
NSLog(@"Sub Name = %@", subItem.name);
NSLog(@"Sub value = %@", subItem.stringValue);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
/**
解析webservice返回的XML成一个NSDictionary
参数:content ,要解析的数据
参数:path ,要解析的XML数据一个根节点
返回:NSDictionary
*/
+ (NSDictionary *)getWebServiceXMLResult:(NSString *) content xpath:(NSString *)path
{
NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
content = [content stringByReplacingOccurrencesOfString:@ "<" withString:@ "<" ];
content = [content stringByReplacingOccurrencesOfString:@ ">" withString:@ ">" ];
content = [content stringByReplacingOccurrencesOfString:@ "xmlns" withString:@ "noNSxml" ];
NSError *docError = nil;
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:content options:0 error:&docError];
if (!docError)
{
NSArray *children = nil;
children = [document nodesForXPath:[NSString stringWithFormat:@ "//%@" ,path] error:&docError];
if (!docError)
{
if (children && [children count]>0)
{
GDataXMLElement *rootElement = (GDataXMLElement *)[children objectAtIndex:0];
NSArray *nodearr = [rootElement children];
for ( int i = 0; i<[nodearr count]; i++) {
GDataXMLElement *element = (GDataXMLElement *)[nodearr objectAtIndex:i];
[resultDict setObject:[element stringValue] forKey:[element name]];
}
}
}
}
[document release];
return [resultDict autorelease];
}
|