2012-03-07 1 views
0

XML에 대한 질문에 백만 번 답변을 받았지만 나에게 맞는 답변을 찾을 수 없다는 것을 알고 있습니다. 여기 내 문제가 있으며 어떤 도움을 환영합니다! 전체 XML 요소를 구문 분석하는 iOS

NSXMLParser에 내 서버에 PHP 스크립트에서 XML 파일을 읽고 그것을 보내면 나중에 내 응용 프로그램의 UITableView를 채우기 위해 그 XML에서 "이름"이라는 모든 요소를 ​​얻을 수있는 방법을 찾을 수 없습니다. 내 목표는 전체 XML 파일을 읽고 "이름"이라는 모든 요소를 ​​가져 와서 NSMutableArray에 저장하여 테이블 뷰를 채 웁니다. 그래서 여기

는 PHP 스크립트를 호출하여 NSXMLParser에 전달 된 XML 코드 :

<?xml version="1.0" encoding="ISO-8859-1"?><?xml-stylesheet type="text/xsl" href="auctions_xsl.xsl"?><auctions> 
<auction> 
    <id>1</id> 
    <name>Leilão Tijuca</name> 
    <description>Casa de vila, ótimo estado e ótima localização. Leiloeiro responsável: Fulano de Tal. Contato pelo telefone 3554-5555</description> 
    <date>2012-03-06</date> 
    <imagepath1>imagem 1</imagepath1> 
    <imagepath2>imagem 2</imagepath2> 
    <imagepath3>imagem 3</imagepath3> 
    <location>Rua São Francisco Xavier, 390 - Tijuca - Rio de Janeiro - RJ</title> 
</auction> 
<auction> 
    <id>2</id> 
    <name>Leilão Barra</name> 
    <description>Cobertura ótimo estado. Leiloeiro responsável Leandro. Contato pelo tel: 3554-9356</description> 
    <date>2012-03-28</date> 
    <imagepath1>001</imagepath1> 
    <imagepath2>002</imagepath2> 
    <imagepath3>003</imagepath3> 
    <location>Avenida das Américas, 500 - Barra - Rio de Janeiro - RJ</title> 
</auction> 
<auction> 
    <id>3</id> 
    <name>Leilão Flamengo</name> 
    <description>Apartamento andar baixo. Localizado em frente ao metrô. Leiloeiro Marcel pelo tel 3554-6678</description> 
    <date>2012-03-18</date> 
    <imagepath1>im1</imagepath1> 
    <imagepath2>im2</imagepath2> 
    <imagepath3>im3</imagepath3> 
    <location>Avenida Oswaldo Cruz, 110 - Flamengo - Rio de Janeiro - RJ</title> 
</auction> 

을 그리고 여기 내 목표 - C 코드의 일부입니다 (잘못된 부분이 주석)

-(void)viewDidLoad { 

[super viewDidLoad]; 
NSURL *url = [NSURL URLWithString:@"http://leandroprellapps.capnix.com/script.php"]; 
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url]; 
allNames = [NSMutableArray arrayWithObjects: nil]; //declared as instance variable in .h file 
xmlParser.delegate = self; 
[xmlParser parse]; 
NSLog(@"%@",allNames); //getting wrong data here 
} 

//and later on 

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

// SUPPOSE TO READ ALL XML FILE AND FIND ALL "name" ELEMENTS 
if ([elementName isEqualToString:@"name"]) { 

    self.currentName = [[NSMutableString alloc] init];  
    } 
} 

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

[self.currentName appendString:string]; //passing the value of the current elemtn to the string 
} 

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

if ([elementName isEqualToString:@"name"]) { 

    NSLog(@"%@", currentName); //show current element 
    [allNames addObject:currentName];//not only is not reading all xml "name" elements but also adding another elements not shown in above NSLog....   
    } 
} 

다음은 NSLog 결과입니다.

2012-03-06 22:51:37.622 Leilao Invest 2.0[10032:f803] Leilão Tijuca 

2012-03-06 22:51:37.623 Leilao Invest 2.0[10032:f803] (
"Leil\U00e3o Tijuca\n\t\tCasa de vila, \U00f3timo estado e \U00f3tima localiza\U00e7\U00e3o. Leiloeiro respons\U00e1vel: Fulano de Tal. Contato pelo telefone 3554-5555\n\t\t2012-03-06\n\t\timagem 1\n\t\timagem 2\n\t\timagem 3\n\t\tRua S\U00e3o Francisco Xavier, 390 - Tijuca - Rio de Janeiro - RJ" 

) 첫 NSLog가 현재 요소의 정확한 이름을 표시하지만 두 번째 NSLog에서, 현재의 요소를 추가 한 후 내 MutableArray을 수행하는 것이

참고, 그냥 "이름"라는 첫 번째 요소와의 무리를 보여줍니다 추가되지 않아야하고 문자열의 인코딩 (NSISOLating1)을 유지하지 않는 다른 요소.

+0

Google XML 파서 (GDataXMLNode)를 사용하여 XML을 구문 분석하는 것이 좋습니다. 더 많은 기능과 가벼움을 가지고 있습니다. XML을 파싱하는 하나의 함수. xPath도 지원합니다. – Raptor

+0

네이티브 xml 파서를 조금 더 사용 해보겠습니다. suceeded가 아니라면 google xml parser에 시도해 보겠습니다. 고마워! – lsp

답변

1

왜냐하면 파서가 임의의 태그 사이에 무엇인가를 발견했을 때 foundCharacters 함수가 호출되기 때문입니다.

첫 번째 태그는 이름과 일치하지 않으므로 'id'입니다. currentName이 초기화되지 않았으므로 currentChangers는 현재 'nall'이므로 '2'값을 추가하지 않습니다. 그런 다음 두 번째 태그는 이름이므로 조건과 일치하고 문자열을 초기화합니다. 이 시점에서, 태그 사이에있는 모든 문자는 currentName에 추가됩니다.

이름 만 구문 분석하려면 한 가지 방법은 currentName에 문자를 추가하기 전에 현재 태그가 '이름'인지 확인하는 것입니다.

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

    // SUPPOSE TO READ ALL XML FILE AND FIND ALL "name" ELEMENTS 
    if ([elementName isEqualToString:@"name"]) { 
     isNameTag = YES; 
     self.currentName = [[NSMutableString alloc] init];  
    } 
} 

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    if (isNameTag) { 
     [self.currentName appendString:string]; //passing the value of the current elemtn to the string 
    } 
} 

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

    if ([elementName isEqualToString:@"name"]) { 
     isNameTag = NO; // disable the flag 
     NSLog(@"%@", currentName); //show current element 
     [allNames addObject:currentName];//not only is not reading all xml "name" elements but also adding another elements not shown in above NSLog....   
    } 
} 
+0

감사합니다. 그것은 다소 일합니다. 이제 이름 만 내 배열에 추가되지만 XML의 모든 "이름"요소를 가져올 수는 없습니다. 첫 번째 요소 만 추가합니다. xml에는 "name"이라는 세 가지 요소가 있습니다. 파서가 모든 XML 파일을 검색하도록하는 방법입니까? – lsp

+0

파일 끝까지 파서 함수가 실행되지 않습니다. – lsp

+0

예, 문서가 끝날 때까지 구문 분석합니다. didEndElement에 구문 분석 된 이름을 기록 했습니까? 여기에는 3 개의 이름이 모두 표시되거나 이름 만 표시됩니까? – Hanon