遍历XML并将属性存储在结构中

I query a device and it returns an XML output with the number of alerts. I want to store each alert as a struct and store all the alerts in a slice.

I have looked through a number of answers for a similar problem but I am having a hard time finding how to parse the attributes of each msg tag and put the attributes into the struct.

Example Code: https://play.golang.org/p/XZMONjRc5q1

I had to add the attr to the vbcAlert struct.

I have made corrections to your example code on the playground.

  • Your XML example was not well-formed; the first <msg> element was missing a closing tag, so there would've been parse errors.
  • Your outer element is not named "xml version". Your outer element is the <alarmlist>, which contains zero or more elements named <msg>.
  • Values contained by <msg> are not elements. They are attributes and must be tagged appropriately.

I imagine this is not the only XML document your code will need to handle in the long run, so I recommend you read the godoc very carefully to understand the tag syntax. Look for introductions to XML on the nets if you're having trouble with some of the terminology.