2013-07-23 4 views
0

을 비 정렬 화 보내고되지 나는 다음과 같은 XML이 :golang의 XML

<wb:sources page="1" pages="1" per_page="50" total="28" xmlns:wb="http://www.worldbank.org"> 
    <wb:source id="11"> 
    <wb:name>Africa Development Indicators</wb:name> 
    <wb:description /> 
    <wb:url /> 
    </wb:source> 
    <wb:source id="31"> 
    <wb:name>Country Policy and Institutional Assessment (CPIA) </wb:name> 
    <wb:description /> 
    <wb:url /> 
    </wb:source> 
</wb:sources> 

내 코드 XML을 구문 분석 :

 type Source struct { 
    Id string `xml:"id,attr"` 
    Name string `xml"wb:name"` 
} 

type Sources struct { 
    XMLName xml.Name `xml"wb:sources"` 
    Sourcez []Source `xml"wb:source"` 
} 

    func GetSources() (*Sources, error) { 
     resp, err := http.Get(sourcesUrl) 
     if err != nil { 
      log.Fatalf("error %v", err) 
      return nil, err 
     } 

     defer resp.Body.Close() 
     s := new(Sources) 
     body, err := ioutil.ReadAll(resp.Body) 
     if err != nil { 
      log.Print(err) 
      return nil, err 
     } 
     log.Printf("body %v", string(body)) 

     xml.Unmarshal(body, &s) 
     return s, nil 

    } 

My code: 

    sources, err := GetSources() 
     if err != nil { 
      log.Panic() 
     } 

     fmt.Printf("%v ", sources) 

는 내가 잘못하고있는 무슨 &{{http://www.worldbank.org sources} []}을 반환 유지를?

답변

0

는에 구조체를 변경 :

type Source struct { 
    Name  string `xml:"name"` 
    Description string `xml:"description"` 
    Url   string `xml:"url"` 
} 

type Sources struct { 
    XMLName xml.Name `xml"sources"` 
    SourceList []Source `xml:"source"` 
} 

하고 일했다!

+0

임 궁금 : 여기

은 예를 단순화하고 작업이다 sources' ? –

3

struct에 wb:을 사용하지 않아야합니다. 하나 WB`에`페이지 = "1"`에서 pages``에서 속성 값을, 예를 들어`1` 얻을 수있는 방법, http://play.golang.org/p/fphHokLprT

+0

단순화 된 예제에 오타가 있으며 테스트 데이터의 이름, 설명 및 URL 데이터를 실제로 구문 분석하지 않습니다. 다음은 작동하는 버전입니다. https://play.golang.org/p/n5JFUk6UC2 –