簡介:採用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];
}