gpt4 book ai didi

ios - 在iPhone中使用NSXmlParser时如何获取xml中标记的路径?

转载 作者:行者123 更新时间:2023-12-01 16:45:39 25 4
gpt4 key购买 nike

我是iPhone开发的新手。在我的应用程序中,有多个具有相同名称的标签。我想获取标签的路径,以便确保获得正确的标签。
我的xml结构就像

<items>
<name></name>
<link></link>
<items>
<name></name>
<link></link>
</items>
</items>

最佳答案

需要完全相同的东西,猜想这是一个古老的问题,但是我会写下实现的内容:

- (void) parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(@"parserDidStartDocument");
self.errorParsingDictionary = [NSMutableDictionary dictionary];
self.nodeStack = [NSMutableArray array];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"didStartElement --> %@", elementName);
[self.nodeStack addObject:elementName]; // Push
NSString *currentPath = [self pathFromNodeStack];
// [self.errorParsingDictionary setObject:[NSMutableDictionary dictionary]
// forKey:currentPath];
[self.errorParsingDictionary setValue:[NSMutableDictionary dictionary]
forKeyPath:currentPath];
}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(@"foundCharacters --> %@", string);
NSString *currentPath = [self pathFromNodeStack];
// NSMutableString *mutableString = [self.errorParsingDictionary objectForKey:currentPath];
id nodeValue = [self.errorParsingDictionary valueForKeyPath:currentPath];
NSMutableString *nodeString = nil;
if (nil==nodeValue || ![nodeValue isKindOfClass:[NSString class]])
{
nodeString = [NSMutableString string];
// [self.errorParsingDictionary setObject:mutableString
// forKey:currentPath];
[self.errorParsingDictionary setValue:nodeString
forKeyPath:currentPath];
}
[nodeString appendString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

NSLog(@"didEndElement --> %@", elementName);
[self.nodeStack removeObjectAtIndex:[self.nodeStack count]-1]; // Pop
}

- (void) parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"parserDidEndDocument");
self.nodeStack = nil;
}

-(NSString*)pathFromNodeStack
{
NSMutableString *path = [NSMutableString string];
for (int i=0; i<self.nodeStack.count; i++)
{
[path appendString:[self.nodeStack objectAtIndex:i]];
if (i!=self.nodeStack.count-1)
{
// If it is not the last object
[path appendString:@"."];
}
}
return path;
}

解析完成后,您现在可以使用字典: self.errorParsingDictionary获取任何路径的值,如下所示:
NSString *nodeValue = [self.errorParsingDictionary valueForKeyPath: @"items.items.name"];

希望这可以帮助。

关于ios - 在iPhone中使用NSXmlParser时如何获取xml中标记的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20184993/

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