在 NSXmlParser 中处理自闭合标签? [英] Handling self-closing tags in NSXmlParser?

查看:32
本文介绍了在 NSXmlParser 中处理自闭合标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何处理 NSXmlparser 中的自闭合标签?没有起始元素和结束元素 -- 是否可以处理以下类型的标签?

How can we can we handle self-closing Tags in NSXmlparser? There is no starting element and end element -- is it possible to handle the following type of Tags?

<ITEM NAME/>
<REG Number/>

推荐答案

任何 XML Parser,包括 NSXMLParser,都应该处理这个:

Any XML Parser, including NSXMLParser, should be treating this:

<ITEMNAME/>

与此 XML 相同:

<ITEMNAME></ITEMNAME>

换句话说,就您编写的解析器代码而言,您应该看到解析器调用的元素回调的开始和结束.为了证明这一点,我将以下示例 XML 放在一个文件中:

In other words, as far as the parser code you write is concerned, you should see both the start and the end of the element callbacks being invoked by the parser. To prove this out, I put the following sample XML in a file:

<top>
    <sample1/>
    <sample2 attr1="a"/>
</top>

然后我实现了以下代码来加载这个文件并解析它:

I then implemented the following code to load this file and parse it:

NSURL *sampleURL = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:sampleURL];
[parser setDelegate:self];
[parser parse];

我的解析器委托方法实现如下:

My parser delegate methods were implemented as follows:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:  (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"Received didStartElement callback for tag: %@", elementName);
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
    NSLog(@"Received didEndElement callback for tag: %@", elementName);
}

当我运行这段代码时,我看到了以下控制台输出:

When I ran this code I saw the following console output:

2012-01-01 22:24:24.011 SampleXML[10248:707] Received didStartElement callback for tag: top
2012-01-01 22:24:24.012 SampleXML[10248:707] Received didStartElement callback for tag: sample1
2012-01-01 22:24:24.013 SampleXML[10248:707] Received didEndElement callback for tag: sample1
2012-01-01 22:24:24.013 SampleXML[10248:707] Received didStartElement callback for tag: sample2
2012-01-01 22:24:24.015 SampleXML[10248:707] Received didEndElement callback for tag: sample2
2012-01-01 22:24:24.015 SampleXML[10248:707] Received didEndElement callback for tag: top

如您所见,我为 sample1 和 sample2 标记同时获得了 didStartElement 和 didEndElement 回调,这就是它应该如何工作的.

As you can see, I got both a didStartElement and didEndElement callback for both the sample1 and sample2 tags, which is how it should be working.

这篇关于在 NSXmlParser 中处理自闭合标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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