将XML解析为JSON,然后再解析为XML。我已将<directory>
XML标记映射为忽略,但是运行xml.Marshal
时,我得到:
<Directory><directory></directory>**MY DATA**</Directory>
我希望输出XML为:
<directory>**MY DATA**</directory>
输出也只是来自输入文件的部分数据;最后的<fn>
,<ct>
,<ln>
标签。对于JSON或XML各自的名称转换,都是如此。
我的golang:
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"os"
)
type Directory struct {
XMLtag xml.Name `xml:"directory" json:"-"` //Locate XML <directory> tag
ContactList []ItemList `xml:"item_list" json:"directory"` //Locate XML <item_list> tag & call it "directory" in JSON
}
type ItemList struct {
LocalContact *LocalContact `xml:"item" json:"contact"` //Locate XML <item> tag & call it "contact" in JSON
}
type LocalContact struct {
Name string `xml:"fn" json:"name"` //Locate XML <fn> tag & call it "name" in JSON
Extension string `xml:"ct" json:"extension"` //Locate XML <ct> tag & call it "extension" in JSON
Long string `xml:"ln" json"ln"` //Locate XML <ln> tag
}
var (
localfile string = os.Getenv("USERPROFILE") + "\\tmp-config.cfg"
)
func main() {
f, err := ioutil.ReadFile(localfile)
if err != nil {
log.Fatal(err)
}
//Read XML into struct
var directory Directory
xml.Unmarshal([]byte(f), &directory)
//Marshal XML to JSON
jsonData, _ := json.Marshal(directory)
fmt.Println(string(jsonData))
//Marshal JSON to XML
directory = Directory{}
json.Unmarshal([]byte(jsonData), &directory)
xmlData, _ := xml.Marshal(directory)
fmt.Println(string(xmlData))
}
我的输入文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- $RCSfile: 000000000000-directory~.xml,v $ $Revision: 1.3 $ -->
<directory>
<item_list>
<item>
<ln> 1002 Shelly </ln>
<fn> Shelly </fn>
<ct> 1002 </ct>
</item>
<item>
<ln> 1003 Chris </ln>
<fn> Chris </fn>
<ct> 1003 </ct>
</item>
<item>
<ln> 1004 Extra </ln>
<fn> Extra </fn>
<ct> 1004 </ct>
</item>
<item>
<ln> 1005 Ray </ln>
<fn> Ray </fn>
<ct> 1005 </ct>
</item>
<item>
<ln> 1006 Kitchen </ln>
<fn> Kitchen </fn>
<ct> 1006 </ct>
</item>
<item>
<ln> 1007 Scott </ln>
<fn> Scott </fn>
<ct> 1007 </ct>
</item>
<item>
<ln> 1008 Heath </ln>
<fn> Heath </fn>
<ct> 1008 </ct>
</item>
<item>
<ln> 1009 Andy </ln>
<fn> Andy </fn>
<ct> 1009 </ct>
</item>
<item>
<ln> 1010 John </ln>
<fn> John </fn>
<ct> 1010 </ct>
</item>
</item_list>
</directory>