0

我的 XML 格式是这样的:

<Rows>
  <Row>
    <style>String</style?
    <thumbnail>String</thumbnail>
  </Row>
  <Row>
    <style>String</style?
    <thumbnail>String</thumbnail>
  </Row>
</Rows>

我如何创建这样的 NSMutableArray ({style = "value"; thumbnail = "value";}.....)

这是我的代码:

-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqualToString:@"style"]) {
       element = [NSString stringWithString:elementName];
       if (!soapResults) {
           soapResults = [[NSMutableString alloc] init];
       }
       elementFound = YES;
    }
    if ([elementName isEqualToString:@"thumbnail1"]) {
       element = [NSString stringWithString:elementName];
       if (!soapResults) {
           soapResults = [[NSMutableString alloc] init];
       }
      elementFound = YES;
    }
  }

-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string

{
    if (elementFound) {
        [soapResults appendString:string];
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI: (NSString*)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"style"]) {
        [rowDict setValue:soapResults forKey:@"style"];
        elementFound = NO;
        soapResults = nil;
    }
   if ([elementName isEqualToString:@"thumbnail1"]) {
       [rowDict setValue:soapResults forKey:@"thumbnail1"];
       elementFound = NO;
       soapResults = nil;
   }
}

如果我这样做,我的格式有误,请帮帮我

提前致谢。

4

1 回答 1

0

创建一个对象类,比如说 SampleObj

* SampleObj.h *

@interface SampleObj : NSObject 
{

    NSString *style;
    NSString *thumbnail;

}

@property (nonatomic,retain) NSString *style,*thumbnail;

* SampleObj.m *

@implementation SampleObj
@synthesize style,thumbnail;

//dealloc your synthesized value;

像这样解析。

NSArray *array=[theXML componentsSeparatedByString:@"<Rows>"];
for(int i=1;i<[array count];i++)
{
   NSArray *arrayRow=[theXML componentsSeparatedByString:@"<Row>"];

   for(int j=1;j<[arrayRow count];j++)
     {
       SampleObj *custobj = [[SampleObj alloc] init];
        NSString *str=[arrayRow objectAtIndex:i];
        NSArray *arr1=[str componentsSeparatedByString:@"<style>"];

        NSString *data=[arr1 objectAtIndex:1];
        NSRange ranfrom=[data rangeOfString:@"</style>"];
        custobj.style =[data substringToIndex:ranfrom.location];

        arr1=[str componentsSeparatedByString:@"< thumbnail >"];
        data=[arr1 objectAtIndex:1];
        ranfrom=[data rangeOfString:@"</thumbnail >"];
        custobj.thumbnail=[data substringToIndex:ranfrom.location];

        [yourarray addObject:custobj];

        [custobj release]


      }
}

如果要使用该对象:

SampleObj *custobj = [yourarray objectAtIndex:rowPosition];
NSLog(@"style : %@", custobj.style);
NSLog(@"thumbnail : %@", custobj.thumbnail);

希望它会有所帮助。抱歉任何错字。

于 2013-10-10T07:34:00.560 回答