iOS 用GDataXMLNode创建和解析XML
原文地址:http://blog.csdn.net/gf771115/article/details/7718403
NSError *error;
// NSString *path = [[NSBundle mainBundle] pathForResource:@"testxml" ofType:@"xml"];
// NSString *content = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//// NSLog(content);
// GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:content options:1 error:&error];
//创建XML
GDataXMLElement *rootElement = [GDataXMLNode elementWithName:@"request"];
GDataXMLElement *element = [self getElementWithName:@"peter" withAge:@"24" withSex:@"male"withAttribute:@"0"];
[rootElement addChild:element];
element = [self getElementWithName:@"Green" withAge:@"26" withSex:@"female" withAttribute:@"1"];
[rootElement addChild:element];
element = [self getElementWithName:@"Susan" withAge:@"28" withSex:@"female" withAttribute:@"1"];
[rootElement addChild:element];
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithRootElement:rootElement];
NSData *data = [document XMLData];
NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(content);
if(error){
NSLog([error localizedDescription]);
}else{
//解析XML
GDataXMLElement *root = [document rootElement];
for (int i=0; i <[rootElement childCount]; i++) {
GDataXMLElement *element = [root childAtIndex:i];
NSLog(@"Element Name = %@", element.name);
NSLog(@"Type = %@", [[element attributeForName:@"type"] stringValue]);
for (int j=0; j<[element childCount]; j++) {
GDataXMLElement *subItem = [element childAtIndex:j];
NSLog(@"Sub Name = %@", subItem.name);
NSLog(@"Sub value = %@", subItem.stringValue);
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。