简介:采用KissXML第三方程序集来实现,需要引入libxml2.dylib
(另需注意运行时可能会提示“libxml/tree.h找不到“的问题,
解决办法: 在项目的 TARGETS 中选择一个目标,在右侧切换到 Build Settings 页,向下找到 Search
Paths 段,其中有一个 Header Search Paths 项,将其值设为:/usr/include/libxml2)如下图:
ProvinceCity.xml文件格式如下图:
程序主要代码如下:
#import"DDXML.h"
#import"DDXMLElementAdditions.h"
@implementation ViewController
//解析XML
staticNSString *kXML =@"//District//Province";
- (void)viewDidLoad
{
[superviewDidLoad];
NSString *path =[[NSStringalloc]initWithString:[[NSBundlemainBundle]pathForResource:@"ProvinceCity"ofType:@"xml"]];
NSData *data = [[NSDataalloc]initWithContentsOfFile:path];
[selfparsedDataFromData:dataandProvince:@"江西省"];
[selfparsedDataFromData:data];
[datarelease];
}
//取特定省份下包含所有城市
-(void)parsedDataFromData:(NSData *)data andProvince:(NSString *)province{
DDXMLDocument *doc = [[DDXMLDocumentalloc]initWithData:dataoptions:0error:nil];
/解析
NSArray *items = [docnodesForXPath:kXMLerror:nil];
for (DDXMLElement *objin items) {
DDXMLNode *aUser = [obj attributeForName:@"Name"];//取属性Name的值
if ([aUser.stringValueisEqualToString:province])
{
NSArray *CityLst = [obj elementsForName:@"City"];//取城市点点列表,保存到数组中
if(CityLst.count>0)//第二层
{
for (DDXMLElement *citysin CityLst) {
DDXMLNode *citynode=[citys attributeForName:@"Name"];
NSLog(@"%@",citynode.stringValue);
}
}
}
}
[doc release];
}
//取所有省份及其下级节点,包含修改操作
-(void)parsedDataFromData:(NSData *)data{
DDXMLDocument *doc = [[DDXMLDocumentalloc]initWithData:dataoptions:0error:nil];
/解析
NSArray *items = [docnodesForXPath:kXMLerror:nil];
for (DDXMLElement *objin items) {
DDXMLNode *aUser = [objattributeForName:@"Name"];//取属性Name的值
//[aUser setStringValue:@"haha!"];//修改属性节点的值
[objaddAttribute:[DDXMLNodeattributeWithName:@"test"stringValue:@"wzh"]];//增加一个属性节点
[objaddAttributeWithName:@"ttt"stringValue:@"343"];//再增加一个属性节点
//[obj setStringValue:@"NewNode"];//设置当前节点的值
DDXMLNode *newnode=[DDXMLNodeelementWithName:@"newNode"];//设置一个新的节点
[obj addChild:newnode];//给obj添加一个节点
DDXMLElement *newdxml = [[objelementsForName:@"newNode"]objectAtIndex:0];//访问刚刚添加的节点
[newdxmladdAttributeWithName:@"nodetwo"stringValue:@"twovalue"];//给刚添加的节点增加增的下级节点,并且下级节点再一个属性值
DDXMLNode *newnode2=[DDXMLNodeelementWithName:@"newNode2"stringValue:@"hello!"];
[newdxmladdChild:newnode2];
}
//保存到沙盒目录下
NSString *path =[[NSStringalloc]initWithFormat:@"%@/xmlData.xml", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]];
NSString *result=[[NSStringalloc]initWithFormat:@"%@",doc];
[resultwriteToFile:pathatomically:YESencoding:NSUTF8StringEncoding error:nil];
//[result2 writeToFile:path atomically:YES];//这种方法不行,保存后会有乱码
[result release];
[path release];
[doc release];
}