GDataXML修改XML文件

GDataXML和KissXML都可以对xml文件进行修改,本文是对GDataXML-HTML的使用方法进行说明,GDataXML-HTML基于谷歌的GDataXML并且支持HTML的解析,详情请见Github,可以直接使用CocoaPods将其导入到工程当中:pod 'GDataXML-HTML', '~> 1.3.0'

删除节点

//本地xml文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"map2" ofType:@"svg"];
//xml字符串
    NSString *xmlStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //读取xml到内存
    GDataXMLElement *element = [[GDataXMLElement alloc] initWithXMLString:xmlStr error:nil];
//搜索xml中的g标签,GDataXML-HTML也支持XPath
    NSArray *result = [element elementsForName:@"g"];
//寻找需要被删除的节点,此处是所有g标签中的最后一个
    GDataXMLNode *node = (GDataXMLNode *)[result lastObject];
    //删除操作
    [element removeChild:node];

增加节点

//创建元素
    GDataXMLElement* pathEle = [GDataXMLNode elementWithName:@"path"];
    //创建id属性
    GDataXMLNode* attr = [GDataXMLNode attributeWithName:@"id" stringValue:@"myid"];
    //为元素添加id属性
    [pathEle addAttribute:attr];
    //添加属性
    GDataXMLNode* attr1 = [GDataXMLNode attributeWithName:@"d" stringValue:@"M20 20 C90 40 130 40 180 20 S250 60 280 20"];
    GDataXMLNode* attr2 = [GDataXMLNode attributeWithName:@"stroke" stringValue:@"#C63300"];
    GDataXMLNode* attr3 = [GDataXMLNode attributeWithName:@"fill" stringValue:@"none"];
    GDataXMLNode* attr4 = [GDataXMLNode attributeWithName:@"style" stringValue:@"stroke-width: 5px;"];
    //将以上4个属性添加到pathEle元素中
    [pathEle addAttribute:attr1];
    [pathEle addAttribute:attr2];
    [pathEle addAttribute:attr3];
    [pathEle addAttribute:attr4];
    //将元素添加为XML文档根元素的子元素
    [element addChild:pathEle];

重新生成XML文件

GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithRootElement:element];
    NSData *xmlData = [doc XMLData];
    NSString *xmlStrrss = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",xmlStrrss);

你可能感兴趣的:(GDataXML修改XML文件)