Jef*_*ern 11 xml cocoa objective-c
给出以下XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<application name="foo">
<movie name="tc" english="tce.swf" chinese="tcc.swf" a="1" b="10" c="20" />
<movie name="tl" english="tle.swf" chinese="tlc.swf" d="30" e="40" f="50" />
</application>
Run Code Online (Sandbox Code Playgroud)
如何访问MOVIE节点的属性("英语","中文","名称","a","b"等)及其相关值?我目前在Cocoa中有遍历这些节点的能力,但我对如何访问MOVIE NSXMLNodes中的数据感到茫然.
有没有办法可以将每个NSXMLNode中的所有值转储到Hashtable中并以这种方式检索值?
我使用的是NSXMLDocument和NSXMLNodes.
Jef*_*ern 12
是!我不知何故回答了自己的问题.
迭代XML文档时,不要将每个子节点指定为NSXMLNode,而是将其指定为NSXMLElement.然后,您可以使用attributeForName函数,该函数返回NSXMLNode,您可以使用stringValue来获取属性的值.
由于我不善于解释事情,这是我的评论代码.这可能更有意义.
//make sure that the XML doc is valid
if (xmlDoc != nil) {
//get all of the children from the root node into an array
NSArray *children = [[xmlDoc rootElement] children];
int i, count = [children count];
//loop through each child
for (i=0; i < count; i++) {
NSXMLElement *child = [children objectAtIndex:i];
//check to see if the child node is of 'movie' type
if ([child.name isEqual:@"movie"]) {
{
NSXMLNode *movieName = [child attributeForName:@"name"];
NSString *movieValue = [movieName stringValue];
//verify that the value of 'name' attribute of the node equals the value we're looking for, which is 'tc'
if ([movieValue isEqual:@"tc"]) {
//do stuff here if name's value for the movie tag is tc.
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有两种选择.如果你继续使用NSXMLDocment并且你有NSXMLNode *一个电影元素,你可以这样做:
if ([movieNode kind] == NSXMLElementKind)
{
NSXMLElement *movieElement = (NSXMLElement *) movieNode;
NSArray *attributes = [movieElement attributes];
for (NSXMLNode *attribute in attributes)
{
NSLog (@"%@ = %@", [attribute name], [attribute stringValue]);
}
}
Run Code Online (Sandbox Code Playgroud)
否则,您可以切换到使用NSXMLParser替代.这是一个事件驱动的解析器,它在解析了元素(以及其他内容)时通知委托.您接下来的方法是解析器:didStartElement:namespaceURI:qualifiedName:attributes:
- (void) loadXMLFile
{
NSXMLParser *parser = [NSXMLParser parserWithContentsOfURL:@"file:///Users/jkem/test.xml"];
[parser setDelegate:self];
[parser parse];
}
// ... later ...
- (void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"movie"])
{
NSLog (@"%@", [attributeDict objectForKey:@"a"]);
NSLog (@"%d", [[attributeDict objectForKey:@"b"] intValue]);
}
}
Run Code Online (Sandbox Code Playgroud)