解析Cocoa中的NSXMLNode属性 [英] Parsing NSXMLNode Attributes in Cocoa

查看:95
本文介绍了解析Cocoa中的NSXMLNode属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下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>

如何访问属性(english,chinese,name,a ,b等)及其关联的MOVIE节点的值?我目前在Cocoa能够遍历这些节点,但我很失去我如何访问MOVIE NSXMLNodes中的数据。

How can I access the attributes ("english", "chinese", "name", "a", "b", etc.) and their associated values of the MOVIE nodes? I currently have in Cocoa the ability to traverse these nodes, but I'm at a loss at how I can access the data in the MOVIE NSXMLNodes.

有一种方法我可以将每个NSXMLNode中的所有值转储到一个Hashtable并以这种方式检索值?

Is there a way I can dump all of the values from each NSXMLNode into a Hashtable and retrieve values that way?

我使用NSXMLDocument和NSXMLNodes。

Am using NSXMLDocument and NSXMLNodes.

推荐答案

是的!我在某种程度上回答了我自己的问题。

YES! I answered my own question somehow.

当迭代遍历XML文档时,而不是将每个子节点分配为NSXMLNode,将其分配为NSXMLElement。然后你可以使用attributeForName函数,它返回一个NSXMLNode,你可以使用stringValue来获取属性的值。

When iterating through the XML document, instead of assigning each child node as an NSXMLNode, assign it as an NSXMLElement. You can then use the attributeForName function, which returns an NSXMLNode, to which you can use stringValue on to get the attribute's value.

由于我不好解释事情,这里是我注释的代码。这可能更有意义。

Since I'm bad at explaining things, here's my commented code. It might make more sense.

//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.
                        }
                    }
            }   
   }

这篇关于解析Cocoa中的NSXMLNode属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆