我正在做一个命令行应用程序,它充当某些 SOAP 服务的接口(interface)。 为了发送和接收一些有效的响应,我必须解析一个自定义 xml(信封),每个 soap 服务都有自己的框架信封,在那个框架中我必须添加我的 buff/文本/信息。
一帧看起来像这样。
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webPosRo.uaic/">
<soapenv:Body>
<web:parseText_XML>
<rawTextInput>HERE</rawTextInput>
</web:parseText_XML>
</soapenv:Body>
如果您查看“此处”,我必须放置我要发送的内容。 我发现使用 encoding/xml 包很奇怪,因为例如我有 6 个服务,每个服务我有一个信封类型。
为了传递它们,我需要像这样制作 6 对不同的结构。
type Envelope struct {
XMLName xml.Name `xml:"Envelope"`
Val1 string `xml:"xmlns:soapenv,attr"`
Val2 string `xml:"xmlns:web,attr"`
CreateBody Body `xml:"soapenv:Body"`
}
type Body struct {
CreateText Text `xml:"web:parseText_XML"`
}
type Text struct {
TextRow []byte `xml:"rawTextInput"`
}
如果我有另一个信封。
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webNpChunkerRo.uaic/">
<soapenv:Body>
<web:chunkText>
<inputText>
</inputText>
</web:chunkText>
</soapenv:Body>
</soapenv:Envelope>
我还有另一个 3 结构对类型。
type Envelope1 struct {
XMLName xml.Name `xml:"Envelope"`
Val1 string `xml:"xmlns:soapenv,attr"`
Val2 string `xml:"xmlns:web,attr"`
CreateBody Body1 `xml:"soapenv:Body"`
}
type Body1 struct {
CreateText Text1 `xml:"web:chunkTest"`
}
type Text1 struct {
TypeRow []byte `xml:"inputText"`
}
我觉得这很奇怪..也是为了解析第一个有命名空间的节点
<soapenv:Envelope ... >
//content
</soapenv:Envelope>
在我 Unmarshall 和 Marshall 之后我得到
<Envelope ... >
//content
</Envelope>
只是第一个注释丢失了命名空间“soapenv”,为了让它完整,我必须创建一个函数来像这样清理它。
func sanitizeEnvelope(buffer []byte) []byte {
var (
StartF = []byte("<Envelope")
FinalF = []byte("</Envelope>")
StartT = []byte("<soapenv:Envelope ")
FinalT = []byte("</soapenv:Envelope>")
)
// Check all the bytes equal to StartF and FinalF
// And replace all with StartT and FinalT
buffer = bytes.Replace(buffer, StartF, StartT, -1)
buffer = bytes.Replace(buffer, FinalF, FinalT, -1)
// return the new sanitize envelope buffer
return buffer
}
有没有更好的解决方案来解析它并包含第一个节点 namespace ?还是可以使用上述 sanitizer 解决方案?
最佳答案
据我所知,您的信封是相同的(从解析/架构的角度来看),因此您可以使用 struct embedding减少结构的数量。
为了进一步减少结构的数量,您可以在结构标签中使用 >
语法一次性包装嵌套的结构字段(xml.Marshal,xml.Unmarshal)
type Envelope struct {
XMLName xml.Name `xml:"Envelope"`
Val1 string `xml:"xmlns:soapenv,attr"`
Val2 string `xml:"xmlns:web,attr"`
}
type Msg1 struct {
Envelope
Input string `xml:"soapenv:Body>web:chunkTest>inputText"`
}
我尚未对此进行完美测试,但它应该足以让您入门。
关于xml - 在 Go 中解析 Xml Envelope Soap 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34343240/