1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

XML 要素名が可変の Unmarshal

Last updated at Posted at 2019-07-08

要素名が可変かつ複数だがその中の属性などはわかっている場合の Unmarshal の方法です。

具体的にはこんな感じ。

<NAMES>
  <!-- 画面ごとの表示名のリスト。プログラムとしては、ProgramX、CustName、お名前や顧客名が欲しい情報 -->
  <Program1 ID="CustName" Name="お名前" />
  <Program2 ID="CustName" Name="顧客名" />
</NAMES>

それを処理するのが以下のコード。

type ItemNames struct {
	Defs []Def `xml:",any"` // ★
}

type Def struct {
	XMLName xml.Name
	ID      string `xml:"ID,attr"`
	Name    string `xml:"Name,attr"`
}

func hoge() error {
	if _, err := os.Stat("itemNames.xml"); err == nil {
		fd, err := os.Open("itemNames.xml")
		if err != nil {
			return err
		}

		content, err := ioutil.ReadAll(fd)
		if err != nil {
			return err
		}
		fd.Close()

		var itemNames ItemNames
		err = xml.Unmarshal(content, &itemNames)
		if err != nil {
			return err
		}

		for _, d := range itemNames.Defs {
			// よしなに
			// d.XMLName.Local
			// d.ID
			// d.Name
		}
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?