TouchXML 解析XML小结

鉴客 发布于 2012/01/10 09:28
阅读 1K+
收藏 0

准备:(在xCode项目中加入对touchXML的支持)

操作步骤如下:

1、下载最新touchXML类库(下载);

2、将步骤1中的类库加入到xCode项目中,操作流程如下图所示:

TOUCHXML解析XML小结 - Milo - JAVA KEY

2-1

TOUCHXML解析XML小结 - Milo - JAVA KEY

2-2

TOUCHXML解析XML小结 - Milo - JAVA KEY

2-3

提示:在实际开发中,为了保证路径一致,而非引用,可以把Copy itmes into destination group’s folder(if needed)”选项打上勾.

3、因为TouchXML使用了libxml2,故需要首先添加libxml2 library(右击FrameworksàaddàExitting Frameworksàlibxml2.dylib),然后在工程编译选项中按如下操作:

TOUCHXML解析XML小结 - Milo - JAVA KEY

3-1{(Header Search Path)--(/usr/include/libxml2)}

TOUCHXML解析XML小结 - Milo - JAVA KEY

3-2{(Other Linker Flags)--(-lxml2)}

4、编写要解析的xml文件(userInfo.xml),源代码如下:

<users>

<user>

<id>CN0001</id>

<name>张三</name>

<gender>01</gender>

<age>23</age>

</user>

<user>

<id>CN0002</id>

<name>张三</name>

<gender>02</gender>

<age>22</age>

</user>

<user>

<id>CN0003</id>

<name>张三</name>

<gender>02</gender>

<age>25</age>

</user>

<user>

<id>CN0004</id>

<name>张三</name>

<gender>01</gender>

<age>21</age>

</user>

</users>

步骤5、编写解析xml的objective-c源代码,如下是点击某个按钮事件触发解析事件:

#pragma mark -

#pragma mark user code

- (void) parseXML:(UIButton *) button

{

NSString *XMLPath = [[[NSBundle mainBundle] resourcePath]

stringByAppendingPathComponent:@"userInfo.xml"

];

NSData *XMLData = [NSData dataWithContentsOfFile:XMLPath];

CXMLDocument *document = [[CXMLDocument alloc] initWithData:XMLData

options:

error:nil

];

//[self parseDire:document];

[self parseRoot:document];

}

//方式一:直接查找

- (void) parseDire:(CXMLDocument *) document

{

NSArray *users = NULL;

users = [document nodesForXPath:@"//user" error:nil];

for (CXMLElement *element in users)

{

if ([element isKindOfClass:[CXMLElement class]])

{

NSMutableDictionary *item = [[NSMutableDictionary alloc] init];

for (int i = ; i < [element childCount]; i++)

{

if ([[[element children] objectAtIndex:i] isKindOfClass:[CXMLElement class]])

{

[item setObject:[[element childAtIndex:i] stringValue]

forKey:[[element childAtIndex:i] name]

];

}

}

NSLog(@"%@", item);

}

}

}

//方式二:从根节点查找

- (void) parseRoot:(CXMLDocument *) document

{

CXMLElement *root = [document rootElement];

NSArray *users = [root children];

for (CXMLElement *element in users)

{

if ([element isKindOfClass:[CXMLElement class]])

{

NSMutableDictionary *item = [[NSMutableDictionary alloc] init];

for (int i = ; i < [element childCount]; i++)

{

if ([[[element children] objectAtIndex:i] isKindOfClass:[CXMLElement class]])

{

[item setObject:[[element childAtIndex:i] stringValue]

forKey:[[element childAtIndex:i] name]

];

}

}

NSLog(@"%@", item);

}

}

}

加载中
返回顶部
顶部