让我试着尽可能清楚地解释我对这个问题的看法。
xml看起来像这样
<Books>
<Book id="1">
<title>Circumference</title>
<author>Nicholas Nicastro</author>
<summary>Eratosthenes and the Ancient Quest to Measure the Globe.</summary>
</Book>
<Book id="2">
<title>Copernicus Secret</title>
<author>Jack Repcheck</author>
<summary>How the scientific revolution began</summary>
</Book>
</Books>
看起来像这样
<Books>
<Book id="1">
<title>Circumference</title>
<author>Nicholas Nicastro</author>
<summary id ='1'>Eratosthenes and the Ancient Quest to Measure the Globe.</summary>
<summary id ='2'>Eratosthenes more info in another tag.</summary>
<summary id ='3'>Eratosthenes and again another tag.</summary>
<summary id ='4'>Eratosthenes and the final tag another one here</summary>
</Book>
<Book id="2">
<title>Copernicus Secret</title>
<author>Jack Repcheck</author>
<summary id ='1'>How the scientific revolution began</summary>
<summary id ='2'>Eratosthenes more info in another tag.</summary>
<summary id ='3'>Eratosthenes and again another tag.</summary>
<summary id ='4'>Eratosthenes and the final tag another one here</summary>
</Book>
</Books>
现在如果我按照上面列出的网站上的说明,它没有解释如何处理摘要2,3,4(我需要解析的xml看起来像这样)以及如何显示它们的输出。我得到的只是最后一行。有没有人知道我怎么能得到其他的(在这种情况下意味着2,3似乎只显示最后一个,因为那可能是currentElementValue中的最后一个)。
我有点困惑,我必须在这里解决属性,还是应该在我的解析器中创建一个新的搜索标签?
答案 0 :(得分:2)
我认为this是您需要查看的内容,您可以从属性中获取id字段的值,并使用该值将其分配给您可以使用的变量。
所以我可能在didStartElement中有这个东西(其中属性是标题中声明的变量):
if([elementName isEqualToString:@"Summary"]){
attributes = attributeDict;
}
然后在我的foundCharacters中有类似的东西:
if([[attributes valueForKey:@"id"] intValue] == 1){
doSomething
}else if([[attributes valueForKey:@"id"] intValue] == 2){
doSomethingElse
}...
等等,直到你把所有数据都拿出来。
N.B。这是100%未经测试的代码,但我相信它可能有用......
答案 1 :(得分:0)
您需要通过将某些容器中的所有值保存为数组来跟踪到目前为止已解析的摘要元素:NSMutableArray。因此,您可以使用NSMutableArray来保存已解析的摘要列表,而不是保留摘要的NSString。
每当您在解析器中遇到摘要时,都不会将NSString摘要设置为您刚刚读取的字符串(它替换旧值并解释为什么您只获取最后一个摘要标记)。而是将它存储为新字符串并将该字符串添加到NSMutableArray。
您链接到的博客文章中的设计问题是它使用keyValueCoding设置Book对象中的属性,这不利于将项添加到数组项中。因此,您需要在解析器中包含对summary元素的一些特殊处理,并向Book类添加允许您将项添加到summary数组的方法。有关如何使用KVC执行此操作,请参阅this post。