gpt4 book ai didi

objective-c - XML 解析,递归 : Making array with arrays and dictionaries

转载 作者:行者123 更新时间:2023-12-03 18:00:10 24 4
gpt4 key购买 nike

考虑这个 XML 结构:

<api>
<status>200</status>
<message>OK</message>
<response>
<item>
<id>1</id>
<image/>
<title>Some title</title>
<text/>
<email>some email</email>
<channels>
<item>
<id>1</id>
<group_id>1</group_id>
<image>/path/to/image.png</image>
<title>Some other title</title>
<text/>
</item>
<item>
<id>2</id>
<group_id>1</group_id>
<image>/path/to/image.png</image>
<title>Some other title</title>
<text/>
</item>
</item>
</response>
</api>

响应下可以有任意数量的项目, channel 下可以有任意数量的项目。实际上这个结构用于很多不同的数据,但通用布局看起来像这样(但我不知道每个 xml 元素的名称。

我有一个 XML 解析器(使用 TBXML 解析器),它工作得很好。我想将此结构解析为 nsarray 和 nsdictionaries 的组合..

现在我得到了以下内容,但我还没有完全实现! (我似乎无法指出我所缺少的东西。

Objective-C 代码:

- (NSArray*) parsedResponse
{
TBXML *xml = [[TBXML alloc] initWithXMLData:self.responseData];
TBXMLElement *rootXML = xml.rootXMLElement;

NSArray *_data;

if(rootXML != nil)
{
TBXMLElement *xml = [TBXML childElementNamed:@"status" parentElement:rootXML];
if(xml != nil)
_data = [NSArray arrayWithObject:[self traverseElement:xml]];
}

return [_data autorelease];
}

- (NSMutableDictionary*) traverseElement:(TBXMLElement*)_element
{
NSMutableDictionary *_items = [[NSMutableDictionary alloc] init];

if(_element != nil)
{
int i = 0;
do {
if(_element == nil)
continue;

// If there is a firstChild, there is subelements
if(_element->firstChild)
{
//need to do some magic here? i can't figure it out..
NSArray *_item = [NSArray arrayWithObject:[self traverseElement:_element->firstChild]];
NSString *key = [NSString stringWithFormat:@"%@%d", [TBXML elementName:_element], i];

[_items setValue:_item forKey:[TBXML elementName:_element]];

}
else
[_items setValue:[TBXML textForElement:_element] forKey:[TBXML elementName:_element]];

i++;

} while ((_element = _element->nextSibling));
}

return [_items autorelease];
}

有什么建议吗?

最佳答案

使用 NSXMLParser 及其委托(delegate)方法。

  parser:didStartElement:namespaceURI:qualifiedName:attributes:

parser:foundCharacters:

parser:didEndElement:namespaceURI:qualifiedName:

您应该引用XML Parsing Guide .

关于objective-c - XML 解析,递归 : Making array with arrays and dictionaries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7825146/

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