KissXML(创建xml和解析xml)

KissXML //创建xml和解析xml

#import "DDXML.h"

 

//xml案例

<?xml version="1.0" encoding="UTF-8"?>

<root flag="www">

<type>reg</type>

<content>

<username>Macro</username>

<password>123456</password>

</content>

<root>

 

/*****  解析xml  *****/

// 创建document

DDXMLDocument *doc = [[DDXMLDocument alloc] initWithData:(NSData *) options:(NSUInteger) error:(NSError *__autoreleasing *)];

// or

DDXMLDocument *doc = [[DDXMLDocument alloc] initWithXMLString:(NSString *) options:(NSUInteger) error:(NSError *__autoreleasing *)];

// 创建根节点

DDXMLElement *root = [doc rootElement];

// 获取root节点的属性节点

DDXMLElement *msgAttribute = [[root attributes] lastObject];

// 获取属性节点的flag

NSString *flag = [msgAttribute valueForKey:@"flag"];// = @"www"

// 获取root节点下的type节点

DDXMLElement *type = [[root elementsForName:@"type"] lastObject];

// 获取type节点的value

NSString *typeValue = type.stringValue;// = @"reg"

// 获取root节点下的content节点

DDXMLElement *content = [[root elementsForName:@"content"] lastObject];

// 获取content节点下的username节点

DDXMLElement *usernameElement = [[content elementsForName@"username"] lastObject];

// 获取username节点的value

NSString *username = usernameElement.stringValue;// = @"Macro"

// 获取content节点下得password节点

DDXMLElement *passwordElement = [[content elementsForName@"password"] lastObject];

// 获取passwordElement节点的value

NSString *password = passwordElement.stringValue;// = @"123456"

 

/*****  创建xml  *****/

// 创建root节点

DDXMLElement *root = [[DDXMLElement alloc] initWithName:@"root"];

// 创建属性flag="www"

DDXMLElement *msgAttribute = [DDXMLElement attributeWithName:@"flag"stringValue:@"www"];

// 把上述属性添加到root节点

[root addAttribute:msgAttribute];

// 创建type节点,并赋值@"reg"

DDXMLElement *type = [[DDXMLElement alloc] initWithName:@"type"stringValue:@"reg"];

// 创建content节点

DDXMLElement *content = [[DDXMLElement alloc] initWithName:@"content"];

// 创建username节点,并赋值@"Macro"

DDXMLElement *username = [[DDXMLElement alloc] initWithName:@"username"stringValue:@"Macro"];

// 创建password节点,并赋值@"123456"

DDXMLElement *password = [[DDXMLElement alloc] initWithName:@"password"stringValue:@"123456"];

// username节点添加到content节点上

[content addChild:username];

// password节点添加到content节点上

[content addChild:password];

// type节点添加到root节点上

[root addChild:type];

// content节点添加到root节点上

[root addChild:content];

// root节点格式化为字符串

NSString *s =[NSString stringWithFormat:@"%@", root];

// 把上述字符串转换为doc文档,自动添加版本等信息

DDXMLDocument *doc = [[DDXMLDocument alloc] initWithXMLString:s options:0 error:nil];

NSLog(@"%@", doc);

posted @ 2015-06-01 10:05  MacroHong  阅读(476)  评论(0)    收藏  举报