【问题标题】:xml parsing in iPhone and getting other tags with same names在 iPhone 中解析 xml 并获取具有相同名称的其他标签
【发布时间】:2009-07-31 12:35:03
【问题描述】:

让我尽可能清楚地解释这个问题的确切含义。

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 中的最后一个)。

我有点困惑,我是不是也必须在这里解决这个属性,还是应该在我的解析器中创建一个新的搜索标签?

【问题讨论】:

    标签: objective-c xml parsing


    【解决方案1】:

    我认为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
    }...
    

    以此类推,直到您获得所有数据为止。

    注意这是 100% 未经测试的代码,但我相信它可能会工作......

    【讨论】:

    • thnx 很多,虽然我不得不说,感觉有点像 mmm 的解决方法,我更喜欢一种更有效的方法,尽管我非常感谢你的意见,如果另一种方法让我失败,我什至可以使用它。
    【解决方案2】:

    您需要通过将所有值保存在某个容器(如数组)中来跟踪到目前为止已解析的摘要元素:NSMutableArray。因此,您可以使用 NSMutableArray 来保存已解析的摘要列表,而不是使用 NSString 来保存摘要。

    每当您在解析器中遇到摘要时,您都不会将 NSString 摘要设置为您刚刚读取的字符串(它会替换旧值并解释为什么您只获得最后一个摘要标记)。相反,您将其存储为一个新字符串并将该字符串添加到您的 NSMutableArray。

    您链接到的博客文章中的设计问题在于它使用 keyValueCoding 来设置 Book 对象中的属性,这不利于将项目添加到数组项目中。因此,您需要在解析器中包含一些对摘要元素的特殊处理,并向 Book 类添加允许您将项目添加到摘要数组的方法。请参阅this post,了解如何使用 KVC 来做到这一点。

    【讨论】:

    • thnx 很多 .. 我要研究一下这个... 看起来很有希望不幸的是,我将不得不阅读关键编码文档以获得更好的理解;)。
    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多