2012-01-05 1 views
2

와 XML 응답 값을 가져옵니다 : 나는 사용자 ID를 추출하고 싶습니다나는 다음과 같은 XML 응답 검색 HTTP를 포스트 후 GDataXML

<result value="OK"> 
    <user id="1"> 
      <name>admin</name> 
      <rank>0</rank> 
      <picture_count>0</picture_count> 
      <comment_count>0</comment_count> 
      <has_profile>1</has_profile> 
    </user> 
</result> 

을, 그러나 나는이 작업을 수행하는 방법을 모르겠어요. GDataXML 파서는 이미 내 프로젝트에 통합되어 있기 때문에 시도했지만 HTML 태그 내부에서 값을 가져 오는 방법을 모르겠습니다.

도와 주시면 감사하겠습니다. XMLParser으로 해결 방법이 없으면 정규 표현식을 사용 하시겠습니까? 이 경우에는 정규 표현식에 대한 해결책을 고맙겠습니다. 저는이 것을별로 잘하지 못합니다.

미리 감사드립니다.

+0

사용자 태그 요소에 대해 'attributeForName'을 사용하여 전체 XML 문서를 검색 할 수 있습니다. 자세한 내용은이 [stackoverflow 링크] (http://stackoverflow.com/questions/3028020/ask-for-an-example-code-for-parsing-xml-and-get-attributes-by-using-gdata- api) –

+0

고마워,하지만 만약 내가'GDataXMLElement * elem = doc.rootElement; NSString * userID = [[elem attributeForName : @ "사용자 ID"] stringValue]; '이것은 null을 반환합니다. – s4lfish

+0

'attributeForName : @ "id"'이 맞습니다. 속성은'id'이며'user id'가 아닙니다. 희망이 도움이됩니다. –

답변

4

이것은 사용자 속성을 검색하는 데 사용하는 코드입니다. 그것은 작동합니다.

NSString* path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"xml"]; 

NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path]; 
NSError *error; 
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData 
                  options:0 error:&error]; 

NSArray *userElements = [doc.rootElement elementsForName:@"user"]; 

for (GDataXMLElement *userEl in userElements) { 

    // Attribute 
    NSString *attribute = [(GDataXMLElement *) [userEl attributeForName:@"id"] stringValue];   
    NSLog(@"attribute for user is %@", attribute); 

    // Name 
    NSArray *names = [userEl elementsForName:@"name"]; 
    if (names.count > 0) { 
     GDataXMLElement *name = (GDataXMLElement *) [names objectAtIndex:0]; 

     NSLog(@"name for user is %@", name.stringValue); 
    } 

    // Rank 
    NSArray *ranks = [userEl elementsForName:@"rank"]; 
    if (ranks.count > 0) { 
     GDataXMLElement *rank = (GDataXMLElement *) [ranks objectAtIndex:0]; 

     NSLog(@"rank for user is %@", rank.stringValue); 
    } 

    // Do the same for other tags...  
} 

[doc release]; 
[xmlData release]; 

test.xml 파일은 xml 응답에서 검색하는 파일과 동일합니다. 따라서이 스 니펫 코드의 두 번째 줄을 변경해야합니다. 어쩌면 initWithDataNSData 방법을 호출 할 수 있습니다.

원하는 위치에이 코드를 넣을 수 있습니다. 어쩌면 당신은 중앙 파서로 작동하는 다른 클래스를 만들 수 있습니다. 이

편집

이 명령에 대해 이전에이 두 줄을 넣어 도움이되기를 바랍니다.

NSString *valAttribute = [(GDataXMLElement *) [doc.rootElement attributeForName:@"value"] stringValue];   
NSLog(@"value attribute for result is %@", valAttribute); 

설명은 매우 간단합니다. doc.rootElement을 사용하면 <result>에서 </result>

+0

대단히 감사합니다. 필자는이 단일 사용자 요소로이 사용자 배열을 작성하지 않았습니다. 이 코드는 매력처럼 작동합니다. – s4lfish

+0

당신을 진심으로 환영합니다. –

+0

작은 질문 : 나중에 'NSArray * resultElements = [doc.rootElement elementsForName : @ "result"];'배열을 작성하여 결과 값을 얻으려고하고 'attributeForName @ "value" 배열은 null입니다. – s4lfish