//DOM : Document Object Model ,一种XML解析的方式,先读取整篇的内容,然后再进行解析,解析速度比较快,如果内出现错误,解析就会失败,iOS不支持DOM解析,goole提供了一个DOM解析的类库(GDataXMLNode)
//注: 使用GDataXMLNode,需要进行2步设置,详情见GDataXMLNode.h 第30行
(1)
self.studentArray = [NSMutableArray arrayWithCapacity:3];
// GDataXMLDocument :用于去管理和读取文件内容
//获取文件路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"xml"];
//读取文件内容
NSError *contentError = nil;
//如果出现错误
if (contentError) {
NSLog(@"%@", contentError);
}
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&contentError];
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:content options:0 error:nil];
//获取根节点
// GDataXMLElement ,节点类
GDataXMLElement *rootElement = [document rootElement];
//找到student的节点
NSArray *studentElements = [rootElement elementsForName:@"student"];
//遍历所有的student节点,封装数据
for (GDataXMLElement *element in studentElements) {
NSLog(@"%@", element);
Student *student = [[Student alloc] init];
student.name = [[[element elementsForName:@"name"] firstObject] stringValue];
student.sex = [[[element elementsForName:@"sex"] firstObject] stringValue];
student.age = [[[element elementsForName:@"age"] firstObject] stringValue];
[_studentArray addObject:student];
}
//打印封装好的数据
for (Student *student in _studentArray) {
NSLog(@"%@", student);
}
(2)
<A>
<B>
<C>
<D>1</D>
<E>2</E>
</C>
<F>
<D>3</D>
<C>
<D>4</D>
</C>
</F>
</B>
</A>
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Xpath" ofType:@"xml"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:content options:0 error:nil];
GDataXMLElement *rootElement = [document rootElement];
//xPath:路径检索,/代表绝对路径,//代表相对路径
//例如:找到E 可以用//C/E 或者//E
NSArray *elements = [rootElement nodesForXPath:@"//E" error:nil];
NSLog(@"%@", elements);
// Do any additional setup after loading the view.
}