gpt4 book ai didi

objective-c - 解析 Cocoa 中的 NSXMLNode 属性

转载 作者:数据小太阳 更新时间:2023-10-29 01:41:30 25 4
gpt4 key购买 nike

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

如何访问 MOVIE 节点的属性(“english”、“chinese”、“name”、“a”、“b”等)及其相关值?我目前在 Cocoa 中具有遍历这些节点的能力,但我不知道如何访问 MOVIE NSXMLNodes 中的数据。

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

我正在使用 NSXMLDocument 和 NSXMLNodes。

最佳答案

是的!我以某种方式回答了我自己的问题。

当遍历 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.
}
}
}
}

关于objective-c - 解析 Cocoa 中的 NSXMLNode 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2962027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com