【问题标题】:How to read the content of an XML tag如何读取 XML 标记的内容
【发布时间】:2010-07-01 04:46:50
【问题描述】:

如何读取这个 XML 的内容?

<Locations>
<Location>4</Location>
</Locations>

我可以解析它,它可以工作,但我无法访问Location (4) 的值。我正在使用:

ZoneCheck *azone;
NSString *url1 = [NSString stringWithFormat:@"%@", azone.location];

【问题讨论】:

  • 您使用什么语言? c#, java, c++, javascript???
  • 我将根据问题底部悬空的代码示例的开头来猜测 Objective-C。
  • 是的 iphone 我明白了 if ([elementName isEqualToString:@"Location"]) { [appDelegate.zone addObject:currentElementValue]; [aZonecheck setValue:currentElementValue forKey:elementName];谢谢
  • 没有足够的信息来回答这个问题。你是如何解析 XML 的?你在使用 NSXMLParser 吗?

标签: objective-c xml parsing


【解决方案1】:

我已经发布了答案,请点击以下链接'https://stackoverflow.com/questions/10877374/how-to-parse-the-attributes-like-in-this-xml-file-through-xml-parser/10877758#10877758'

首先取一个布尔变量。然后编写以下代码。也许对你有帮助,我几天前已经完成了相关工作。

第一个 .h 文件

@interface EventsViewController : UIViewController <NSXMLParserDelegate>
{
    NSMutableArray *_locationArray;
    BOOL isLocation;
}

然后在 .m 文件中你应该写这个。

//在ViewDidLoad中

- (void)viewDidLoad
{
    [super viewDidLoad];
    _locationArray = [[NSMutableArray alloc] init];

    NSURL * fileURL = [NSURL fileURLWithPath:xmlString];
    NSXMLParser * parser = [[NSXMLParser alloc] initWithContentsOfURL:fileURL];
    [parser setDelegate:self];
    [parser parse];
}

// 现在在 xml 解析器委托方法中 pragma mark - NSXMLParser 委托方法

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

    if ([elementName isEqualToString:@"Locations"]) {
        isLocation = YES;
    }
    else if ([elementName isEqualToString:@"Location"] && isLocation){
        NSLog(@"Location is: %@ ",elementName);
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
   if ([elementName isEqualToString:@"Location"] && isLocation){
        NSLog(@"Location is: %@ ",string);
        [locationArray addObject:string];  
    }
}

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

    if ([elementName isEqualToString:@"Location"]) {
        isLocation=NO;
    }
}

注意:最后 _locationArray 将包含所有位置的 id。

【讨论】:

    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多