diff --git a/common/serialize/test_test.go b/common/serialize/test_test.go index e9c78404..2e7ea18a 100644 --- a/common/serialize/test_test.go +++ b/common/serialize/test_test.go @@ -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 := ` + + + + +` + + // 示例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(`%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) + } + } +}