本文整理汇总了Golang中github.com/clbanning/mxj.NewMapXml函数的典型用法代码示例。如果您正苦于以下问题:Golang NewMapXml函数的具体用法?Golang NewMapXml怎么用?Golang NewMapXml使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewMapXml函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestMobileSitemaps
func TestMobileSitemaps(t *testing.T) {
doc := etree.NewDocument()
root := doc.CreateElement("root")
data := URL{"loc": "/mobile", "mobile": true}
expect := []byte(`
<root>
<loc>/mobile</loc>
<mobile:mobile/>
</root>`)
SetBuilderElementValue(root, data.URLJoinBy("loc", "host", "loc"), "loc")
SetBuilderElementValue(root, data, "mobile")
buf := &bytes.Buffer{}
doc.WriteTo(buf)
mdata, _ := mxj.NewMapXml(buf.Bytes())
mexpect, _ := mxj.NewMapXml(expect)
if !reflect.DeepEqual(mdata, mexpect) {
t.Error(`Failed to generate sitemap xml thats deferrent output value in URL type`)
}
}
示例2: TestImageSitemaps
func TestImageSitemaps(t *testing.T) {
doc := etree.NewDocument()
root := doc.CreateElement("root")
data := URL{"loc": "/images", "image": []URL{
{"loc": "http://www.example.com/image.png", "title": "Image"},
{"loc": "http://www.example.com/image1.png", "title": "Image1"},
}}
expect := []byte(`
<root>
<image:image>
<image:loc>http://www.example.com/image.png</image:loc>
<image:title>Image</image:title>
</image:image>
<image:image>
<image:loc>http://www.example.com/image1.png</image:loc>
<image:title>Image1</image:title>
</image:image>
</root>`)
SetBuilderElementValue(root, data, "image")
buf := &bytes.Buffer{}
doc.WriteTo(buf)
mdata, _ := mxj.NewMapXml(buf.Bytes())
mexpect, _ := mxj.NewMapXml(expect)
if !reflect.DeepEqual(mdata, mexpect) {
t.Error(`Failed to generate sitemap xml thats deferrent output value in URL type`)
}
}
示例3: IsCompatible
// IsCompatible compares two XML strings and returns true if the second has all the same element names and value types as the first.
// The elements don't have to be in the same order.
// The second XML string can have additional elements not present in the first.
func IsCompatible(a, b string) (compatible bool, err error) {
aMap, err := mxj.NewMapXml([]byte(a), true)
if err != nil {
return
}
bMap, err := mxj.NewMapXml([]byte(b), true)
if err != nil {
return
}
return isStructurallyTheSame(aMap, bMap)
}
示例4: Emulator
// Emulator returns appropriate path to QEMU emulator for a given architecture
func (d *Driver) Emulator(arch string) (string, error) {
switch arch {
case "x86_64":
case "i686":
default:
return "", utils.FormatError(fmt.Errorf("Unsupported architecture(%s).Only i686 and x86_64 supported", arch))
}
out, err := d.Run("virsh capabilities")
if err != nil {
return "", utils.FormatError(err)
}
m, err := mxj.NewMapXml([]byte(out))
if err != nil {
return "", utils.FormatError(err)
}
v, _ := m.ValuesForPath("capabilities.guest.arch", "-name:"+arch)
// fixing https://github.com/dorzheh/deployer/issues/2
if len(v) == 0 {
return "", utils.FormatError(fmt.Errorf("Can't gather a KVM guest information for architecture %s.", arch))
}
return v[0].(map[string]interface{})["emulator"].(string), nil
}
示例5: confAmq
func confAmq(
amqConfPath string,
confPolicyEntry string,
confLevelDB string) string {
xmlStr := gd.StrFromFilePath(amqConfPath)
xmlMap, _ := mxj.NewMapXml([]byte(xmlStr))
step := Step{&xmlMap}
// flow
(&step).
SetJvmHeap("80").
RemoveLogQuery().
InsertPolicyEntry(confPolicyEntry).
RemoveKahadb().
AddLevelDB(confLevelDB).
FixAmpersand().
FixColonKey()
// dd(xmlMap)
resultBytes, _ := mxj.AnyXmlIndent(
xmlMap["beans"], "", " ", "beans")
r := gd.BytesToString(resultBytes)
return r
}
示例6: main
func main() {
m, err := mxj.NewMapXml(data)
if err != nil {
fmt.Println("err:", err)
}
fmt.Println(m.StringIndentNoTypeInfo())
doc, err := m.XmlIndent("", " ")
if err != nil {
fmt.Println("err:", err)
}
fmt.Println(string(doc))
val, err := m.ValuesForKey("child1")
if err != nil {
fmt.Println("err:", err)
}
fmt.Println("val:", val)
mxj.XmlGoEmptyElemSyntax()
doc, err = mxj.AnyXmlIndent(val, "", " ", "child1")
if err != nil {
fmt.Println("err:", err)
}
fmt.Println(string(doc))
}
示例7: main
func main() {
// parse XML into a Map
m, merr := mxj.NewMapXml(xmlData)
if merr != nil {
fmt.Println("merr:", merr.Error())
return
}
// extract the 'list3-1-1-1' node - there'll be just 1?
// NOTE: attribute keys are prepended with '-'
lstVal, lerr := m.ValuesForPath("*.*.*.*.*", "-name:list3-1-1-1")
if lerr != nil {
fmt.Println("ierr:", lerr.Error())
return
}
// assuming just one value returned - create a new Map
mv := mxj.Map(lstVal[0].(map[string]interface{}))
// extract the 'int' values by 'name' attribute: "-name"
// interate over list of 'name' values of interest
var names = []string{"field1", "field2", "field3", "field4", "field5"}
for _, n := range names {
vals, verr := mv.ValuesForKey("int", "-name:"+n)
if verr != nil {
fmt.Println("verr:", verr.Error(), len(vals))
return
}
// values for simple elements have key '#text'
// NOTE: there can be only one value for key '#text'
fmt.Println(n, ":", vals[0].(map[string]interface{})["#text"])
}
}
示例8: collect
func collect(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
_ = fmt.Sprintf("Username: %s | Password: %s", username, password)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
mxj.XmlCharsetReader = charset.NewReader
m, err := mxj.NewMapXml(body) // unmarshal
if err != nil {
log.Fatal(err)
}
// Single path
path := m.PathForKeyShortest("avg01")
val, err := m.ValueForPath(path)
if err != nil {
log.Fatal(err)
}
fmt.Println(val)
// Multi-path
paths := m.PathsForKey("percent")
for _, path := range paths {
val, err := m.ValueForPath(path)
if err != nil {
log.Fatal(err)
}
fmt.Println(val)
}
io.WriteString(w, "Success")
}
}
示例9: getParsedMap
func getParsedMap(xmlData []byte) {
m, err := mxj.NewMapXml(xmlData)
if err != nil {
panic("error mapping file")
}
xmlMap = m
}
示例10: Decode
func (tree *XMLHandler) Decode() (err error) {
if len(tree.Content) == 0 {
err = fmt.Errorf("XMLHandler.FileContent is empty!")
return
}
//err = xml.Unmarshal(tree.FileContent, &tree.Value)
tree.Value, err = mxj.NewMapXml(tree.Content, true)
return
}
示例11: TestAttrWithoutTypedef
func TestAttrWithoutTypedef(t *testing.T) {
doc := etree.NewDocument()
root := doc.CreateElement("root")
data := URL{"loc": "/videos", "video": URL{
"thumbnail_loc": "http://www.example.com/video1_thumbnail.png",
"title": "Title",
"description": "Description",
"content_loc": "http://www.example.com/cool_video.mpg",
"category": "Category",
"tag": []string{"one", "two", "three"},
"player_loc": Attrs{"https://f.vimeocdn.com/p/flash/moogaloop/6.2.9/moogaloop.swf?clip_id=26", map[string]string{"allow_embed": "Yes", "autoplay": "autoplay=1"}},
}}
expect := []byte(`
<root>
<video:video>
<video:thumbnail_loc>http://www.example.com/video1_thumbnail.png</video:thumbnail_loc>
<video:title>Title</video:title>
<video:description>Description</video:description>
<video:content_loc>http://www.example.com/cool_video.mpg</video:content_loc>
<video:tag>one</video:tag>
<video:tag>two</video:tag>
<video:tag>three</video:tag>
<video:category>Category</video:category>
<video:player_loc allow_embed="Yes" autoplay="autoplay=1">https://f.vimeocdn.com/p/flash/moogaloop/6.2.9/moogaloop.swf?clip_id=26</video:player_loc>
</video:video>
</root>`)
SetBuilderElementValue(root, data, "video")
buf := &bytes.Buffer{}
// doc.Indent(2)
doc.WriteTo(buf)
mdata, _ := mxj.NewMapXml(buf.Bytes())
mexpect, _ := mxj.NewMapXml(expect)
// print(string(buf.Bytes()))
if !reflect.DeepEqual(mdata, mexpect) {
t.Error(`Failed to generate sitemap xml thats deferrent output value in URL type`)
}
}
示例12: TestNewsSitemaps
func TestNewsSitemaps(t *testing.T) {
doc := etree.NewDocument()
root := doc.CreateElement("root")
data := URL{"loc": "/news", "news": URL{
"publication": URL{
"name": "Example",
"language": "en",
},
"title": "My Article",
"keywords": "my article, articles about myself",
"stock_tickers": "SAO:PETR3",
"publication_date": "2011-08-22",
"access": "Subscription",
"genres": "PressRelease",
}}
expect := []byte(`
<root>
<news:news>
<news:keywords>my article, articles about myself</news:keywords>
<news:stock_tickers>SAO:PETR3</news:stock_tickers>
<news:publication_date>2011-08-22</news:publication_date>
<news:access>Subscription</news:access>
<news:genres>PressRelease</news:genres>
<news:publication>
<news:name>Example</news:name>
<news:language>en</news:language>
</news:publication>
<news:title>My Article</news:title>
</news:news>
</root>`)
SetBuilderElementValue(root, data, "news")
buf := &bytes.Buffer{}
doc.WriteTo(buf)
mdata, _ := mxj.NewMapXml(buf.Bytes())
mexpect, _ := mxj.NewMapXml(expect)
if !reflect.DeepEqual(mdata, mexpect) {
t.Error(`Failed to generate sitemap xml thats deferrent output value in URL type`)
}
}
示例13: Xml2Struct
func Xml2Struct(xdata []byte, Nesting bool) string {
m, err := mxj.NewMapXml(xdata)
if err != nil {
panic(err)
}
paths := m.LeafPaths()
if Nesting {
return "Not implement yet..."
} else {
RootName, RootStruct, RestStructs := XmlPath2SrtructLinesNoNesting(paths)
return RootDatas2Struct(RootName, RootStruct, RestStructs)
}
}
示例14: TestVideoSitemaps
func TestVideoSitemaps(t *testing.T) {
doc := etree.NewDocument()
root := doc.CreateElement("root")
data := URL{"loc": "/videos", "video": URL{
"thumbnail_loc": "http://www.example.com/video1_thumbnail.png",
"title": "Title",
"description": "Description",
"content_loc": "http://www.example.com/cool_video.mpg",
"category": "Category",
"tag": []string{"one", "two", "three"},
}}
expect := []byte(`
<root>
<video:video>
<video:thumbnail_loc>http://www.example.com/video1_thumbnail.png</video:thumbnail_loc>
<video:title>Title</video:title>
<video:description>Description</video:description>
<video:content_loc>http://www.example.com/cool_video.mpg</video:content_loc>
<video:tag>one</video:tag>
<video:tag>two</video:tag>
<video:tag>three</video:tag>
<video:category>Category</video:category>
</video:video>
</root>`)
SetBuilderElementValue(root, data, "video")
buf := &bytes.Buffer{}
doc.WriteTo(buf)
mdata, _ := mxj.NewMapXml(buf.Bytes())
mexpect, _ := mxj.NewMapXml(expect)
if !reflect.DeepEqual(mdata, mexpect) {
t.Error(`Failed to generate sitemap xml thats deferrent output value in URL type`)
}
}
示例15: HandleResponse
func (rt ResponseTransformMiddleware) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *SessionState) error {
_, versionPaths, _, _ := rt.Spec.GetVersionData(req)
found, meta := rt.Spec.CheckSpecMatchesStatus(req.URL.Path, req.Method, versionPaths, TransformedResponse)
if found {
thisMeta := meta.(*TransformSpec)
// Read the body:
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
// Put into an interface:
var bodyData interface{}
switch thisMeta.TemplateMeta.TemplateData.Input {
case tykcommon.RequestXML:
mxj.XmlCharsetReader = WrappedCharsetReader
bodyData, err = mxj.NewMapXml(body) // unmarshal
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "outbound-transform",
"server_name": rt.Spec.APIDefinition.Proxy.TargetURL,
"api_id": rt.Spec.APIDefinition.APIID,
"path": req.URL.Path,
}).Error("Error unmarshalling XML: ", err)
}
case tykcommon.RequestJSON:
json.Unmarshal(body, &bodyData)
default:
json.Unmarshal(body, &bodyData)
}
// Apply to template
var bodyBuffer bytes.Buffer
err = thisMeta.Template.Execute(&bodyBuffer, bodyData)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "outbound-transform",
"server_name": rt.Spec.APIDefinition.Proxy.TargetURL,
"api_id": rt.Spec.APIDefinition.APIID,
"path": req.URL.Path,
}).Error("Failed to apply template to request: ", err)
}
res.ContentLength = int64(bodyBuffer.Len())
res.Header.Set("Content-Length", strconv.Itoa(bodyBuffer.Len()))
res.Body = ioutil.NopCloser(&bodyBuffer)
}
return nil
}