当前位置: 首页>>代码示例>>Golang>>正文


Golang mxj.NewMapXml函数代码示例

本文整理汇总了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`)
	}
}
开发者ID:yaotian,项目名称:go-sitemap,代码行数:25,代码来源:builder_url_test.go

示例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`)
	}
}
开发者ID:Staylett,项目名称:go-sitemap-generator,代码行数:31,代码来源:builder_url_test.go

示例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)
}
开发者ID:vvirgitti,项目名称:mockingjay-server,代码行数:14,代码来源:comparisons.go

示例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

}
开发者ID:weldpua2008,项目名称:deployer,代码行数:27,代码来源:driver.go

示例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
}
开发者ID:Mooxe000,项目名称:mooxe-docker-activemq,代码行数:27,代码来源:confAmq.go

示例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))
}
开发者ID:Richardphp,项目名称:noms,代码行数:26,代码来源:gonuts9.go

示例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"])
	}
}
开发者ID:Richardphp,项目名称:noms,代码行数:34,代码来源:gonuts5.go

示例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")
	}
}
开发者ID:kkirsche,项目名称:monitCollector,代码行数:32,代码来源:collector.go

示例9: getParsedMap

func getParsedMap(xmlData []byte) {
	m, err := mxj.NewMapXml(xmlData)
	if err != nil {
		panic("error mapping file")
	}
	xmlMap = m
}
开发者ID:dspencerr,项目名称:Go-Open-XML-Parser,代码行数:7,代码来源:mxjUnwrap.go

示例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
}
开发者ID:re-pe,项目名称:go-dtree,代码行数:9,代码来源:xmlhandler.go

示例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`)
	}
}
开发者ID:ikeikeikeike,项目名称:go-sitemap-generator,代码行数:44,代码来源:builder_url_test.go

示例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`)
	}
}
开发者ID:Staylett,项目名称:go-sitemap-generator,代码行数:43,代码来源:builder_url_test.go

示例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)
	}
}
开发者ID:postfix,项目名称:xj2s,代码行数:13,代码来源:xj2s.go

示例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`)
	}
}
开发者ID:Staylett,项目名称:go-sitemap-generator,代码行数:38,代码来源:builder_url_test.go

示例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
}
开发者ID:TykTechnologies,项目名称:tyk,代码行数:50,代码来源:res_handler_transform.go


注:本文中的github.com/clbanning/mxj.NewMapXml函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。