unmarshalling混合对象类型的xml数组

时间:2017-02-23 18:10:21

标签: xml go polymorphism unmarshalling

我正在处理收到的XML,其中包含一个无序的消息列表,其中每条消息可以是几种不同类型之一。订单并不重要。

我已经找到了一种方法来做我想做的事情(经过多次努力,这是学习的第3天),但我还是如何强有力地处理意外的消息类型

这里有一些代码

package main

import (
  "encoding/xml"
  "fmt"
)

func main() {

  data := `<Envelope>
             <Body>
               <Response>
                 <Messages>
                   <Greeting>
                     <From>Fred</From>
                   </Greeting>
                   <Reminder>
                     <Time>12</Time>
                     <Subject>Lunch at Joe's</Subject>
                   </Reminder>
                   <NewThing>Report me!</NewThing>
                   <Reminder>
                     <Time>6</Time>
                     <Subject>Catch the train</Subject>
                   </Reminder>
                   <Greeting>
                     <From>Mary</From>
                     <Extra>Hi</Extra>
                   </Greeting>
                 </Messages>
                 <MessageCount>3</MessageCount>
               </Response>
             </Body>
           </Envelope>`

  type Greeting struct {
    From string 
  }

  type Reminder struct {
    Time int
    Subject string
  }

  type TopLevel struct {
    Messages struct {
      GreetingList []Greeting `xml:"Greeting"`
      ReminderList []Reminder `xml:"Reminder"`
    } `xml:"Body>Response>Messages"`
  }

  var reply TopLevel

  err := xml.Unmarshal([]byte(data), &reply) 
  if err != nil {
    fmt.Println(err)
    return
  }

  for _, reminder := range reply.Messages.ReminderList {
    fmt.Printf("Reminder: '%s' at %d\n", reminder.Subject, reminder.Time)
  }

  for _, greeting := range reply.Messages.GreetingList {
    fmt.Printf("Greetings From: %s\n", greeting.From)
  }

}

输出

Reminder: 'Lunch at Joe's' at 12
Reminder: 'Catch the train' at 6
Greetings From: Fred
Greetings From: Mary

我还希望能够找到意外类型的消息,既不是<Greeting>也不是<Reminder>,例如<NewThing>,而不事先了解新事物(等等)

Warning: Unexpected message type: NewThing.

我是否应该考虑某种方式来获得一个通用对象列表?或者以某种方式使用XMLname + innerxml字符串的结构?不知道如何处理这些不同类型的单个列表。

线索?

1 个答案:

答案 0 :(得分:1)

您可以使用, any, innerxml标记处理意外的XML元素。

代码更改为(run full example at go playground

  type Any struct {
    XMLName xml.Name 
    Content string   `xml:",innerxml"`
  }

  type TopLevel struct {
    Messages struct {
      GreetingList   []Greeting `xml:"Greeting"`
      ReminderList   []Reminder `xml:"Reminder"`
      UnexpectedList []Any      `xml:",any"`
    } `xml:"Body>Response>Messages"`
  }

  ...

  for _, unexpected := range reply.Messages.UnexpectedList {
    fmt.Printf("Unexpected: %s containing '%s'\n", unexpected.XMLName, unexpected.Content)
  }

输出

Reminder: 'Lunch at Joe's' at 12
Reminder: 'Catch the train' at 6
Greetings From: Fred
Greetings From: Mary
Unexpected: { NewThing} containing 'Report me!'
Unexpected: { NewerThing} containing '<Fruit>Apple</Fruit><Sales>42</Sales>'