0
<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. 

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

4

3 回答 3

1

在 iOS 中解析 XML 是一个艰苦的过程。使用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);

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

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

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

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

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

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

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

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

Bikes.xml 文件

于 2013-06-10T12:15:15.590 回答
0

这是我常用的模板。不需要第三方框架。其中大部分来自 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
}

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

于 2013-06-10T14:02:35.677 回答
0

只需使用NSXMLParser类来解析 xml 文件。使用 NSXMLParser 类的委托方法。委托可以识别您的元素,元素的开始,元素的结束,它还可以识别文档的开始,文档的结束。

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

下面的委托方法可用于检测元素的 statrt

- (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"])
于 2013-06-11T04:29:53.563 回答