在Go中解析Xml Envelope Soap的最佳方法

时间:2015-12-17 19:59:40

标签: xml soap go envelope

我正在做一个命令行应用程序,它充当某些SOAP服务的接口。 为了发送和回复一些有效的响应,我必须解析一个自定义的xml(信封),每个soap服务都有自己的框架信封,在那个框架中我必须添加我的buff / text / info。

一帧看起来像这样。

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

如果你看看&#34; HERE&#34;我必须放置我要发送的内容。 我发现使用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>

只是第一个音符失去了名称空间&#34; soapenv&#34;为了使它完整,我必须制作一个像这样消毒它的功能。

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
}

有没有更好的解决方案来解析它,还包括第一个节点namsepace?或者像上面的清洁解决方案一样好吗?

1 个答案:

答案 0 :(得分:0)

据我所知,你的信封是相同的(从解析/架构的角度来看),所以你可以使用struct embedding来减少结构数量。

为了进一步减少结构的数量,您可以使用struct标签中的>语法一次性包装嵌套的结构域(xml.Marshalxml.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"`
}

我没有对此进行完美测试,但它应该足以让你开始。

相关问题