feat(serialize): 添加 XML 和 JSON 互相转换的功能

- 新增 SuperMaps 和 Map 结构体用于解析和生成 XML 数据
- 实现了 XML 到 JSON 和 JSON 到 XML 的转换功能
- 添加了处理复杂 ID 的 XML 解析逻辑
- 在测试文件中增加了 XML 和 JSON 转换的测试用例
This commit is contained in:
2025-07-02 22:35:41 +08:00
parent ffc39f5462
commit 6a20aa4a4b

View File

@@ -1,7 +1,10 @@
package serialize
import (
"encoding/json"
"encoding/xml"
"fmt"
"strings"
"testing"
"github.com/apcera/termtables"
@@ -47,3 +50,112 @@ func TestInit(t *testing.T) {
fmt.Println(table.Render())
}
// SuperMaps 表示XML根节点
type SuperMaps struct {
XMLName xml.Name `xml:"superMaps" json:"-"`
Maps []Map `xml:"maps" json:"maps"`
}
// Map 表示XML中的每个地图节点
type Map struct {
ID string `xml:"id,attr" json:"id"`
Name string `xml:"name,attr" json:"name"`
X string `xml:"x,attr" json:"x"`
Y string `xml:"y,attr" json:"y"`
Galaxy string `xml:"galaxy,attr" json:"galaxy,omitempty"`
}
func TestXml(t *testing.T) {
// 示例XML数据
xmlData := `<?xml version="1.0" encoding="UTF-8"?>
<superMaps>
<maps id="1" name="传送舱" x="" y=""/>
<maps id="4" name="船长室" x="" y=""/>
<maps id="10 11 12 13" name="克洛斯星" galaxy="1" x="358" y="46"/>
</superMaps>`
// 示例JSON数据
jsonData := `{
"maps": [
{
"id": "1",
"name": "传送舱",
"x": "",
"y": ""
},
{
"id": "4",
"name": "船长室",
"x": "",
"y": ""
},
{
"id": "10 11 12 13",
"name": "克洛斯星",
"galaxy": "1",
"x": "358",
"y": "46"
}
]
}`
// 1. 解析XML并转换为JSON
fmt.Println("=== XML 到 JSON ===")
superMaps := &SuperMaps{}
err := xml.Unmarshal([]byte(xmlData), superMaps)
if err != nil {
fmt.Printf("解析XML失败: %v\n", err)
return
}
jsonOutput, err := json.MarshalIndent(superMaps, "", " ")
if err != nil {
fmt.Printf("转换为JSON失败: %v\n", err)
return
}
fmt.Println(string(jsonOutput))
// 2. 解析JSON并转换为XML
fmt.Println("\n=== JSON 到 XML ===")
newSuperMaps := &SuperMaps{}
err = json.Unmarshal([]byte(jsonData), newSuperMaps)
if err != nil {
fmt.Printf("解析JSON失败: %v\n", err)
return
}
xmlOutput, err := xml.MarshalIndent(newSuperMaps, "", " ")
if err != nil {
fmt.Printf("转换为XML失败: %v\n", err)
return
}
// 添加XML声明
xmlWithHeader := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlOutput)
fmt.Println(string(xmlWithHeader))
// 3. 解析复杂ID的XML并处理
fmt.Println("\n=== 解析复杂ID的XML ===")
parseComplexID(xmlData)
}
// 解析复杂ID的XML并处理
func parseComplexID(xmlData string) {
superMaps := &SuperMaps{}
err := xml.Unmarshal([]byte(xmlData), superMaps)
if err != nil {
fmt.Printf("解析XML失败: %v\n", err)
return
}
// 处理每个地图项
for _, m := range superMaps.Maps {
// 处理包含多个ID的情况
if strings.Contains(m.ID, " ") {
ids := strings.Fields(m.ID)
fmt.Printf("地图名称: %s, 拆分后的ID: %v\n", m.Name, ids)
} else {
fmt.Printf("地图名称: %s, ID: %s\n", m.Name, m.ID)
}
}
}