go語言解析xml文件

1、xml示例

<Managed xmlns="aa">
    <Function xmlns="bb">
      <Cell>
        <Block xmlns="cc">
          <Info>
            <beamIndex>18</beamIndex>
            <ssbIndex>0</ssbIndex>
          </Info>
          <Info>
            <beamIndex>19</beamIndex>
            <ssbIndex>1</ssbIndex>
          </Info>
        </Block>
      </Cell>
    </Function>
  </Managed>

2、Go語言代碼

package main

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"os"
)

type Managed struct {
	Function Function `xml:"Function"`
}
type Function struct {
	Cell Cell `xml:"Cell"`
}
type Cell struct {
	Block Block `xml:"Block"`
}
type Block struct {
	Info []Info `xml:"Info"`
}
type Info struct {
	BeamIndex int `xml:"beamIndex"`  //一定要注意xml文件中小寫,而結構體參數要大寫
	SsbIndex  int `xml:"ssbIndex"`
}

func main() {
	//將文件讀取成字節數組
	content, err := ioutil.ReadFile("E:\\test.xml")
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(9)
	}
	var ps Managed
	//反序列化xml
	xml.Unmarshal(content, &ps)
	beamLen := len(ps.Function.Cell.Block.Info)
	ssbIndex2Beam := make(map[int]int)
	for i := 0; i < beamLen; i++ {
		ssbIndex := ps.Function.Cell.Block.Info[i].SsbIndex
		ssbIndex2Beam[ssbIndex] = ps.Function.Cell.Block.Info[i].BeamIndex
	}
	fmt.Println(ssbIndex2Beam)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章