【问题标题】:Parsing xml data and storing it using core data iOS解析xml数据并使用核心数据iOS存储
【发布时间】:2013-06-06 00:32:40
【问题描述】:
<content name="Bikes" last_updated_time="">
 <bike name="MGP30" image_url="Mobile_App/images/mgp30_bike_banner.png">
  <tspecs>
    <image url="images/our-bikes/mgp30.png"/>
    <image url="images/our-bikes/mgp30_tech_spec/1.jpg"/>
    <image url="images/our-bikes/mgp30_tech_spec/2.jpg"/>
    <image url="images/our-bikes/mgp30_tech_spec/3.jpg"/>
    <image url="images/our-bikes/mgp30_tech_spec/4.jpg"/>
    <image url="images/our-bikes/mgp30_tech_spec/5.jpg"/>
    <image url="images/our-bikes/mgp30_tech_spec/6.jpg"/>
    <image url="images/our-bikes/mgp30_tech_spec/7.jpg"/>
    <spec>
      <name>Engine Type</name>
      <value>4 strokes liquid cooled DOHC</value>
    </spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
    <spec></spec>
  </tspecs>
  <photos></photos>
  <workshop></workshop>
 </bike>
 <bike name="GP125" image_url="Mobile_App/images/gp125_bike_banner.png"></bike>
</content>


This is the first time I am working with xml parsing using core data.I have the above xml data which i receive from the server. I am not bale to understand how to create the relationships between the entities. How do I parse it and keep storing it using core data. 

Content 是以 Bikes 作为子元素的根对象。每个 Bike 元素都有一个 tspecs、照片和车间数据。每个 tspecs 都有一组图像和一组规格数据。每个规格数据都有一个名称和值。

【问题讨论】:

  • 图片和规格有关系吗?
  • 没有关系

标签: ios core-data xml-parsing


【解决方案1】:

解析 XML 在 iOS 中是一个艰苦的过程。使用GDataXML将xml解析成数组格式对应的字典如下。

#define kBikeName  @"name"
#define kBikeImageURL @"image_url"
#define kBikeImages @"image"
#define kURL @"url"

#define kBikeSpecs @"spec"
#define kBikeSpecName @"name"
#define kBikeSpecValue @"value" 

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Bikes" ofType:@"xml"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];

GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithData:fileData
                                                          encoding:NSUTF8StringEncoding
                                                             error:nil];

NSArray *tempBikes = [document nodesForXPath:@"//content/bike" error:nil];

NSMutableArray *bikes = [NSMutableArray array];
for (GDataXMLElement *element in tempBikes) {
    NSMutableDictionary *bike = [NSMutableDictionary dictionary];
    NSString *bikeName = [[element attributeForName:kBikeName] stringValue];
    bike[kBikeName] = bikeName;

    NSString *imageURL = [[element attributeForName:kBikeImageURL] stringValue];
    bike[kBikeImageURL] = imageURL;

    NSArray *tempImages = [element nodesForXPath:@"tspecs/image" error:nil];//elementsForName:@"image"];
    NSMutableArray *images = [NSMutableArray array];
    for (GDataXMLElement *imageElement in tempImages) {
        NSString *url = [[imageElement attributeForName:kURL]stringValue];
        if (url) {
            [images addObject:url];
        }
    }

    if (images) {
        bike[@"Images"] = images;
    }

    NSArray *tempSpecs = [element nodesForXPath:@"tspecs/spec" error:nil];//elementsForName:@"spec"];
    NSMutableArray *specs = [NSMutableArray array];
    for (GDataXMLElement *specElement in tempSpecs) {

        NSMutableDictionary *specDict = [NSMutableDictionary dictionary];

        NSString *specName = [[specElement elementsForName:kBikeSpecName][0]stringValue];
        if (specName) {
             specDict[kBikeSpecName] = specName;
        }
        NSString *specValue = [[specElement elementsForName:kBikeSpecValue][0]stringValue];
        if (specValue) {
             specDict[kBikeSpecValue] = specValue;
        }

        if ([[specDict allKeys] count]) {
             [specs addObject:specDict];
        }

    }

    if (specs) {
        bike[@"Specs"] = specs;
    }

    [bikes addObject:bike];
}

NSLog(@"%@",bikes);

现在您有了字典对象数组。你本可以组成NSManagedObjects 仪式。但是,如果您将来想使用 JSON,这将提供更多可重用的代码。

您应该至少拥有三个实体。如果您愿意,您还可以创建 Bike TechnicalSpec,它与自行车具有一对一的关系,与图像和规格具有一对多的关系。但这似乎没有必要。

  1. 自行车(与自行车图像和规格的一对多关系)
  2. 自行车图片(与自行车的关系一对一)
  3. 自行车规格(与自行车的关系一对一)

第三方库MagicalRecord 提供无代码数据导入。但它要求您拥有实体的唯一 ID。

例如:如果有一个实体Bike,它应该有一个bikeID。 BikeImage 应该有 bikeImageID 和 BikeSpec 应该有 bikeSpecID。由于您没有这些,因此无法使用。但我这么说好像你决定改变结构,这些可以包括在内,以利用这个很棒的功能。

设置实体之间的正确关系和反向关系。枚举解析后的数组。执行以下步骤

  1. 创建一个新的自行车对象,设置它的值
  2. 创建图像实例,将先前创建的自行车对象设置为其父对象。只需要一侧。另一边将由核心数据解决。
  3. 对规格也重复相同的步骤 2。
  4. 保存上下文。

这不会限制重复条目的创建。

Bikes.xml file

【讨论】:

  • 我知道 xml 解析,我的问题是使用核心数据存储这个解析的 xml。但是,我已经设法编写了我的一段代码来做同样的事情。但我不确定我的数据是否已添加到数据库中。因为 [fetchedResultsController.fetchedObjects count] 返回 0。我可以手动检查我的数据库以查看是否有我输入的数据。
  • @Manpreet 在问题中提到了 XML 的标题解析。我会更新以包含核心数据的详细信息。
  • 所以现在我可以解析我的数据并将其保存到核心数据中。我能够使用 fetchRequest 检索数据。但是如果我尝试使用 fetchedResultsController 来获取它,self.fetchedResultsController.fetchedObjects 返回 nil
【解决方案2】:

这是我常用的模板。不需要第三方框架。其中大部分来自 Apple 的Event-Driven Programming Guide。我会为任何代码拼写错误道歉,因为我从应用程序中删除了它并试图让它对你来说有点通用。不过,链接实际上是实质内容。

@implementation XMLParser

- (XMLParser *) initXMLParser {
    appDelegate = (PWMSledUpdateAppDelegate *) [[UIApplication sharedApplication]delegate];
    return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"firstElement"])
    {
        //You now have your First Element name. I typically use an NSMutableDictionary to house the info
        //In your example XML above you'd want to look for "content"
    }
    else if ([elementName isEqualToString:@"secondElement"])
    {
        //Second element name. Do something with it.
        //In your example XML above you'd want to look for "bike"
    }
    //else if, etc, etc
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
        //"string" is your current element's value.
        //using your example the value for content.bike.tspecs.spec.name = "Engine Type"
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"firstElement"])
    {
          NSLog(@"Read key \"%@\" with value \"%@\"",elementName, currentElementValue);
        //you've now reached the end of your first element.
        return;
    }
    else if ([elementName isEqualToString:@"secondElement"])
    {
        //you've now reached the end of your second element.
        return;
    }
    //else if etc, etc
    {
        NSLog(@"Read key \"%@\" with value \"%@\"",elementName, currentElementValue);
        [currUpdate setValue:currentElementValue forKey:elementName];
        currentElementValue = nil;
    }
}

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

    if ( [elementName isEqualToString:@"firstElement"]) 
    {
            if (!myAttributes)
            {
                NSMutableArray *myAttributes = [[NSMutableArray alloc] init];
            }
        NSString *myName = [attributeDict objectForKey:@"name"];
        NSString *myLastUpdate = [attributeDict objectForKey:@"last_updated_time"];
        }
        //else it etc, etc
}

关于容纳我通常使用 NSMutableDictionary 运行的 XML 数据,并结合了具有直观命名约定的自定义类,因此我可以将其称为 myClass.name、myClass.lastUpdated、[myClass.name objectForKey @"MGP30"]..

【讨论】:

    【解决方案3】:

    只需使用 NSXMLParser 类来解析 xml 文件。使用 NSXMLParser 类的委托方法。 delegate 可以识别你的元素,元素的开头,元素的结尾,它也可以识别文档的开头,文档的结尾。

    通过检查您的元素名称是否匹配,您可以将字符串(即数据)保存到数组中并使用该数组添加核心数据

    下面的委托方法可以用来检测元素的状态

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

    检测元素结束的委托方法

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

    总是将值添加到 didEndElement 中的数组。

    你可以像这样检查你当前的元素是否匹配

    if ([elementName isEqualToString:@"firstElement"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多