xml - 制作 xml 以在 golang 后的 http 中发送

标签 xml go xml-parsing http-post

以下是我期望形成的请求 xml

<custom key="234234e324e4">
<document name="sample" location="http://example.com">
</document>
</custom>

为了制作这个 xml,我使用了以下 go 代码

 type Documentxml struct {
    XMLName  xml.Name `xml:"document"`
    Name  string   `xml:"name,attr"`
    Location string   `xml:"location,attr"`
}
type DeleteXml struct {
    XMLName  xml.Name    `xml:"custom"`
    Key   string      `xml:"key,attr"`
    Document Documentxml `xml:"document"`
}

和下面的代码将值插入其中

var requestxml DeleteXml
    requestxml.Key = "12321321"
    requestxml.Document.Name = "sample"
    requestxml.Document.Location = "www.//sample.com"
bytexml, err := xml.Marshal(&requestxml)
	client := &http.Client{}
	url := "http://localhost:8080/searchblox/api/rest/docdelete"
	// build a new request, but not doing the POST yet
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bytexml))
	if err != nil {
		fmt.Println(err)
	}
req.Header.Add("Content-Type", "application/xml; charset=utf-8")
	// now POST it
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(resp)

但是这里形成的请求并不像我预期的那样形成 形成的请求 xml 是:{{ } 12321321{{ } sample www.//sample.com}} 请提出这里出了什么问题

最佳答案

您的 XML 定义是正确的,您得到的是预期的格式。但是在你的问题中。字段 requestxml.Document.Location 的 URL 格式值不正确,不确定这是否是您服务器的问题。

播放链接:https://play.golang.org/p/oCkteDAVgZ

输出:

<custom key="12321321">
  <document name="sample" location="http://www.sample.com"></document>
</custom>

编辑:

可能是您的服务器需要带有 header 的 XML。就像下面-

<?xml version="1.0" encoding="UTF-8"?>
<custom key="12321321">
  <document name="sample" location="http://www.sample.com"></document>
</custom>

您的带有标题的更新代码,播放链接:https://play.golang.org/p/n4VYXxLE6R

关于xml - 制作 xml 以在 golang 后的 http 中发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45232693/

相关文章:

javascript - 获取具有最大值的节点的id

xml - XSLT:检查 XML 元素是否在 xpath 中有父元素

winapi - 如何获取windows应用程序的位置和区域(如 "Google Chrome")?

Golang 如何保证数据在一个 goroutine 中完成,同时被另一个 goroutine 访问

java - 从 SAX java XML 解析器,我如何知道 "DOCTYPE"关键字的大小写?

PHP、SimpleXML、解码 CDATA 中的实体

c# - 如何将 XML 转换为 List<string> 或 String[]?

go - Hyperledger Fabric V1.0 中日期范围的复合键形成

c++ - 使用 RapidXml 解析日文汉字时出错

java - Java 中的 XML 管道