iOS 用GDataXMLNode创建和解析XML

时间:2022-08-17 14:41:29

原文地址: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);

}

}

}