我正在研究需要解析某些xml的iPhone项目。 xml可能包含或不包含默认名称空间。我需要知道如何解析xml以防使用默认名称空间。由于我需要同时阅读一个写xml,我倾向于使用KissXML,但我愿意提供建议。(吻)XML xpath和默认名称空间
这是我的代码:
NSString *content = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:@"bookstore" ofType:@"xml"] encoding:NSUTF8StringEncoding error:nil];
DDXMLDocument *theDocument = [[DDXMLDocument alloc] initWithXMLString:content options:0 error:nil];
NSArray *results = [theDocument nodesForXPath:@"//book" error:nil];
NSLog(@"%d", [results count]);
它适用于该XML预期:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
</book>
</bookstore>
但是当XML有一个命名空间,这样,它停止工作:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore xmlns="[INSERT RANDOM NAMESPACE]">
<book category="COOKING">
<title lang="en">Everyday Italian</title>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
</book>
</bookstore>
当然,我可以预处理字符串并删除xmlns,尽管这感觉像是一种丑陋的黑客。处理这个问题的正确方法是什么?
无数小时的谷歌搜索,研究,拉毛......我无法感谢你。 – caoimghgin