2017-03-10 18 views
1

属性と値で次のXMLを解析しようとしています。私は、次のGo to構文解析するXML toタグ属性

"StrDoc": [ 
    { 
     "Doc": [ 
     { 
      "Key": "cui", 
      "Value": "c0162311" 
     }, 
     { 
      "Key": "display_title", 
      "Value": "Androgenetic alopecia" 
     }, 
     { 
      "Key": "source", 
      "Value": "GHR" 
     }, 
     { 
      "Key": "source_url", 
      "Value": "http://ghr.nlm.nih.gov/condition/androgenetic-alopecia" 
     } 
     ], 
     "Score": [ 
     { 
      "Score": "0.59509283" 
     } 
     ] 
    }, 

所望の出力は、私が達成しようとしてきた

"Doc": [ 
      { 
       "cui": "c0162311", 
       "display_title": "Androgenetic alopecia", 
       "source": "GHR", 
       "Value": "GHR", 
       "source_url": "http://ghr.nlm.nih.gov/", 
       "Score": "0.59509283" 
      } 
      ] 

だろうが生成さ

type Response struct { 
    StrDoc []Str `xml:"result>doc"` 
} 

type Str struct { 
    Doc []Doc `xml:"str"` 
    Score []Score `xml:"float"` 
} 

type Doc struct { 
    Key string `xml:"name,attr"` 
    Value string `xml:",chardata"` 
} 

type Score struct { 
    Score string `xml:",chardata"` 
} 

を作ってみた

<result name="response" numFound="10775" start="0" maxScore="0.59509283"> 
    <doc> 
     <str name="cui">c0162311</str> 
     <str name="display_title">Androgenetic alopecia</str> 
     <str name="source">GHR</str> 
     <str name="source_url">http://ghr.nlm.nih.gov/condition/androgenetic-alopecia</str> 
     <float name="score">0.59509283</float> 
    </doc> 

これは何時間もあり、私は方法を見つけていないまだ。

答えて

1

カスタムUnmarshalXMLメソッドを使用して、マップに内部XMLを非整列化することができます

type Result struct { 
    Doc Doc `xml:"doc"` 
} 

type Doc struct { 
    Elems map[string]string 
} 

func (doc *Doc) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) { 
    type entry struct { 
     Key string `xml:"name,attr"` 
     Value string `xml:",chardata"` 
    } 
    e := entry{} 
    doc.Elems = map[string]string{} 
    for err = d.Decode(&e); err == nil; err = d.Decode(&e) { 
     doc.Elems[e.Key] = e.Value 
    } 
    if err != nil && err != io.EOF { 
     return err 
    } 
    return nil 
} 

遊び場を:https://play.golang.org/p/87v_vTXpB-

+0

ありがとうございました!これは本当に助けになった!私はそれがXMLを含むファイルを開くと動作するようにすることはできません。 https://play.golang.org/p/G8n8Ql6DVx 私が試したものです。 test.xmlファイルには、複数の 'dox'タグを持つXMLが含まれています。 – leandermelms

+0

@leandermelms新しい質問をして、あなたのXML文書のより良い例と結果として望むものを提供する必要があるかもしれません。 –