【问题标题】:JSON/XML parsing iphone NSPredicateJSON/XML 解析 iphone NSPredicate
【发布时间】:2011-03-09 21:02:04
【问题描述】:

我正在尝试创建一个使用 xml 或 json 来显示一些内容的小应用程序。

我有很多“观点”,我想从她的 id 中只选择一个。

XML 看起来像这样(如果你愿意,我可以输入 json,但它很难阅读):

<?xml version="1.0" encoding="utf-8"?>
<views>
    <view id="home" type="nav">
        <title>Help</title>
        <section id="1">
        <title>Aide</title>
        <item id="1" link="dev_mac">Dev Mac</item>
        <item id="2" link="dev_iphone">Dev iPhone</item>
        <item id="3" link="examples">Examples</item>
        </section>
    </view>
    <view id="dev_mac" type="nav">
        <nav_title>Help</nav_title>
        <content_title>Dev Mac</content_title>
        <text>balbalbalblablablalbalblalbal</text>
        <section id="1">
        <item id="1" link="lesson_1">Lesson 1</item>
        <item id="2" link="download">Downlaod</item>
        </section>
    </view>
    <view id="download" type="content">
        <nav_title>Dev Mac</nav_title>
        <title>Lesson 1</title>
        <content_text>balblablalbalblalbalb</content_text>
        <content_title>A. UIKit</content_title>
        <content_text>UIKit is .....</content_text>
    </view>
</views>

我有一个包含 3 个 NSDictionary(第 3 个视图)的数组。

如何通过她的 id 只选择一个视图?

提前致谢

BiB1

【问题讨论】:

    标签: iphone xml json parsing nspredicate


    【解决方案1】:

    您不能直接在 XML 上使用 NSPredicate。您必须将 XML(或 JSON)解析为一些标准的 Cocoa 容器(NSArray 等),然后在上面使用它。

    您能够直接过滤 XML 的唯一方法是使用 XPath 之类的东西,尽管您必须使用 libxml 来执行此操作。

    【讨论】:

    • 是的,我知道,我不想直接在 XML 上使用 NSPredicate。我的 XML 数据使用 XMLReader 转换为 NSDictionary。但我没有找到如何使用 NSPredicate 从我的 NSDictionary(或 NSArray)中的 id 中选择“父项”
    【解决方案2】:

    它应该可以工作 - 只要数据变量实际上是一个包含键为“id”的字典的数组

    NSArray *data =  <your xml>
    NSString *currentViewId = @"home";
    NSArray *filterd = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(id == %@)", currentViewId]];
    

    【讨论】:

      【解决方案3】:

      尝试将 xml 重新格式化为 plist(您可以使用 xcodes plist 编辑器或自己滚动)使用:

      <plist version="1.0">
       <array>
          <dict>
              <key>Title</key><string>Home</string>
              <key>Image</key><string>Home.png</string>
          </dict>
          <dict>
              <key>Title</key><string>Car</string>
              <key>Image</key><string>Car.png</string>
          </dict>
      </array>
      </plist
      

      在 .h 文件中:

      NSArray *Views_List;
      

      在 .m 文件中:

         NSString *Views_DataPath = [[NSBundle mainBundle] pathForResource:@"nameOfYourPlist" ofType:@"plist"];   
          Views_List = [[NSArray alloc] initWithContentsOfFile:Views_DataPath];
      

      然后访问每个字典:

      [[Views_List objectAtIndex: 0] valueForKey:@"Title"];
      

      在本例中,(0) 将返回 'Home'

      【讨论】:

      • 不幸的是,如果视图以不同的顺序发送,我无法使用 objectAtIndex
      猜你喜欢
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2011-10-13
      • 1970-01-01
      相关资源
      最近更新 更多