Objective c NSXMLParser无法在iPhone中添加所有对象?
当我尝试使用NSXMLParser解析XML文件时,我无法解析所有元素。。XML响应如下所示:Objective c NSXMLParser无法在iPhone中添加所有对象?,objective-c,nsxmlparser,Objective C,Nsxmlparser,当我尝试使用NSXMLParser解析XML文件时,我无法解析所有元素。。XML响应如下所示: <List> <Details> <AId>1</AId> <Date>10/31/2012</Date> <Time>11:00 AM</Time> <User> <Employee>
<List>
<Details>
<AId>1</AId>
<Date>10/31/2012</Date>
<Time>11:00 AM</Time>
<User>
<Employee>
<Name>Rosy</Name>
</Employee>
<Company>
<Customer>
<CustName>Williams</CustName>
<CustPhone>1232322</CustPhone>
</Customer>
</Company>
</User>
</Details>
<Details>
<AId>2</AId>
<Date>10/31/2012</Date>
<Time>11:30 AM</Time>
<User>
<Employee>
<Name>Mary</Name>
</Employee>
<Company>
<Customer>
<CustName>Christopher</CustName>
<CustPhone>123233323</CustPhone>
</Customer>
</Company>
</User>
</Details>
</List>
我怎样才能得到它。。。。。无法理解我哪里出了问题….您在DiEndElement方法中使用以下代码,它将帮助您
-(void)parser:(NSXMLParser*)parser
didEndElement:(NSString*)elementName
namespaceURI:(NSString*)namespaceURI
qualifiedName:(NSString*)qualifiedName
{
if ([elementName isEqualToString:@"list"]) {
return;
}
else if ([elementName isEqualToString:@"Details"]){
[yourarray addObject:yourDictionary];
}
else{
if (currentElementValue.length>0) {
[yourDictionary setObject:currentElementValue forKey:elementName];
currentElementValue = nil;
NSLog(@"this is the offer details---%@",[yourDictionary description]);
}
}
}
-(void)parser:(NSXMLParser*)parser
foundCharacters:(NSString*)string
{
currentElementValue=[NSString stringWithString:[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]];
}
- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
currentElementValue = [[NSMutableString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
}
您声明的currentElementValue是什么?NSMutableString*currentElementValue;我应该把currentElementValue=someelement放在哪里,我不想要所有的元素。我不想要CustPhone..我该怎么做?在我的代码中,当我出错时..使用正确的XML解析,例如内置在libxml2中的DOM解析。它更快、更轻量级,唯一的缺点是它是基于C的库。
-(void)parser:(NSXMLParser*)parser
didEndElement:(NSString*)elementName
namespaceURI:(NSString*)namespaceURI
qualifiedName:(NSString*)qualifiedName
{
if ([elementName isEqualToString:@"list"]) {
return;
}
else if ([elementName isEqualToString:@"Details"]){
[yourarray addObject:yourDictionary];
}
else{
if (currentElementValue.length>0) {
[yourDictionary setObject:currentElementValue forKey:elementName];
currentElementValue = nil;
NSLog(@"this is the offer details---%@",[yourDictionary description]);
}
}
}
-(void)parser:(NSXMLParser*)parser
foundCharacters:(NSString*)string
{
currentElementValue=[NSString stringWithString:[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]];
}
- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
currentElementValue = [[NSMutableString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
}