XML解析
解析xml经常使用库: GData
底层使用系统的libxml2库, 使用的时候添加libxml2
(1)导入GData库, 直接拖进来
(2)设置头文件搜索路径
Build Setting--->header search Path
添加 /usr/include/libxml2
(3)添加libxml二进制库
Build Phases ---> Link Binary
添加 libxml2.dylib
(4)如果是arc的工程
Build Phases ---> Compile Source File
GDataXmlNode.m(非arc的)
GDataXMLNode
获取当前节点的值
- (NSString *)stringValue;
//获取当前节点子节点的个数
- (NSUInteger)childCount;
//获取子节点数组
- (NSArray *)children;
//根据索引获取子节点
- (GDataXMLNode *)childAtIndex:(unsigned)index;
GDataXMLElement
//根据节点名字获取所有的节点名为name的节点数组
- (NSArray *)elementsForName:(NSString *)name;
//获取节点的属性
- (NSArray *)attributes;
//根据属性名获取属性节点
- (GDataXMLNode *)attributeForName:(NSString *)name;
GDataXMLDocument
//创建文档树
- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding error:(NSError **)error;
//获取跟节点
- (GDataXMLElement *)rootElement;
//根据xpath 语法 获取 指定的节点数组
- (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error;
-—————————————————————————————————-
// 取文件 -> data
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”xml2” ofType:@”txt”]];
// 读取整个xml文档
GDataXMLDocument \*doc = \[\[GDataXMLDocument alloc\] initWithData:data options:0 error:nil\];
/\*\* 这种方法也是可以的
NSString \*xmlStr = \[\[NSString alloc\] initWithContentsOfFile:\[\[NSBundle mainBundle\] pathForResource:@"xml" ofType:@"txt"\] encoding:NSUTF8StringEncoding error:nil\];
GDataXMLDocument \*doc2 = \[\[GDataXMLDocument alloc\] initWithXMLString:xmlStr options:0 error:nil\];
\*/
// 用xpath取出所有的book结点
NSArray \*bookElementArray = \[doc.rootElement nodesForXPath:@"//book" error:nil\];
// 把book结点搞到我们自定义的book对象中去
for (GDataXMLElement \*bookElement in bookElementArray) \{
// bookElement --> BookItem
// NSLog(@"%@", \[self getBookItemWithElement:bookElement\]);
BookItem \*book = \[\[BookItem alloc\] initWithElement:bookElement\];
NSLog(@"%@", book);
\}
还没有评论,来说两句吧...