iOS 中操作 xml 文件主要通过 libxml2 库实现
加载xml文件
那么,加载xml文件的目的是为了创建 GDataXmlDocument 对象, 可以通过 NSString, NSData 作为其构造函数的参数来创建:例如:
NSString * xml = [NSString stringWithContentsOfFile:PATH encoding:NSUTF8StringEncoding error:nil];
GDataXMLDocument * doc = [[GDataXMLDocument alloc]initWithXMLString:xml options:0 error:nil];
获取xml中的所有节点
通过 xpath 获取的结果是一个 NSArray 数组,其中的每个元素都是一个 GDataXmlDocument 对象,可以通过 stringValue 来获取xml中的属性值。通过 children 来获取当前节点下的所有子节点。
NSURL * url = [[NSURL alloc]initWithString:@"http://rss.sina.com.cn/sina_all_opml.xml"];
NSString * xml = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
GDataXMLDocument * doc = [[GDataXMLDocument alloc]initWithXMLString:xml options:0 error:nil];
NSArray * arr = [doc nodesForXPath:@"/opml/body/outline" error:nil];
for (GDataXMLElement * elem in arr) {
NSString * strTitleLevel1 = [elem attributeForName:@"title"].stringValue;
NSLog(@"==========================");
NSLog(@"%@", strTitleLevel1);
NSLog(@"==========================");
// 当前元素下的所有子元素
NSArray * arrChild = [elem children];
for (GDataXMLElement * eChild in arrChild) {
NewsItem * item = [[NewsItem alloc]init];
item.title = [eChild attributeForName:@"title"].stringValue;
item.xmlUrl = [eChild attributeForName:@"xmlUrl"].stringValue;
item.text = [eChild attributeForName:@"text"].stringValue;
item.type = [eChild attributeForName:@"type"].stringValue;
item.htmlUrl = [eChild attributeForName:@"htmlUrl"].stringValue;
NSLog(@"%@", item);
}
}
获取xml中的节点属性值
// "//ComeChannel/Item" 代表选取所有 ComeChannel/Item 子元素,而不管它们在文档中的位置
NSArray * arr = [doc nodesForXPath:@"//ComeChannel/Item" error:nil];
for (GDataXMLElement * elem in arr) {
// 这是遍历xml中字段带属性的那部分
NSArray * attrs = elem.attributes;
NSString * strValue = [elem attributeForName:@"value"].stringValue;
NSLog(@"%@", strValue);
}
命名空间
// 定义当前 xml 中所有的域空间
// 为了避免冲突定义的
NSDictionary * dict = @{@"book":@"http://www.baidu.com",@"xmlns":@"http://www.sina.com.cn"};
// 所有的节点前都需要加上命名空间的标志
NSArray * arr = [doc nodesForXPath:@"/xmlns:root/xmlns:books/xmlns:book/book:name" namespaces:dict error:nil];
for (GDataXMLElement * elem in arr) {
NSLog(@"%@", elem.stringValue);
}