Iphone json解析xml

这个是一段xml文件,下面要做的是解析这个xml文件。

<pigletlist>
<piglet id="1">
    <name>Nifnif</name>
</piglet>
<piglet id="2">
    <name>Nufnuf</name>
</piglet>
<piglet id="3">
    <name>Nafnaf</name>
</piglet>
</pigletlist>

这个是程序运行结果:

      id = 1; 

        name = Nifnif; 

    }, 

       { 

       id = 2; 

        name = Nufnuf; 

    }, 

       { 

         id = 3; 

        name = Nafnaf; 

     } 

 )

 

 


// 初始化一个数组,将解析的数据放在数组里
NSMutableArray *res = [[NSMutableArray alloc] init];

// 加载当前文件,此时文件名字为piglets.xml
NSString *XMLPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"piglets.xml"];
NSData *XMLData  = [NSData dataWithContentsOfFile:XMLPath];

//通过NSData方式创建CXMLDocument也可以通过字符串的方式,在这里就不说了
   CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:XMLData options:0 error:nil] autorelease];

//创建一个数组,以存放我们从xml中得到的节点

NSArray *nodes = NULL;
//寻找节点为piglet的所有节点 

nodes = [doc nodesForXPath:@"//piglet" error:nil];

for (CXMLElement *node in nodes) {
 NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
 int counter;
 for(counter = 0; counter < [node childCount]; counter++) {
  // 从节点中取出值,按照键值对存储在NSMutableDictionary
  [item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
 }

 // 取得节点属性值,并存储在NSMutableDictionary
 [item setObject:[[node attributeForName:@"id"] stringValue] forKey:@"id"];  // <------ this magical arrow is pointing to the area of interest

 [res addObject:item];
 [item release];
}

// and we print our results
NSLog(@"%@", res);
[res release];


NSString * value = [[[node childAtIndex:counter] stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
 if ([value length] != 0){
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] localName]];

}

posted @ 2010-11-16 10:42  SsQq  阅读(1269)  评论(0编辑  收藏  举报