xml.Unmarshall 多根 XML 在 Go

标签 xml go

有一个 API,我需要连接并从中获取数据。没有办法更新 API。

对于错误,有两种类型的响应:

<error>Database Error</error>

对于正常响应:

<response>
  <device id="1">Test Device</device>
</response>

或像这样:

<response>
  <user age="16">
    <username>TestUser</username>
    <role>user</role>
  </user>
</response>

我尝试实现的是将一个结构设置为 XmlResponse所以我可以先检查它是否有错误,然后将预期类型作为结构的成员。

以下是我为 API 实现的数据类型

type XmlResponse struct {
    Error  *XmlError
    Result *XmlResult
}

type XmlError struct {
    XMLName xml.Name `xml:"error"`
    Error   string   `xml:",innerxml"`
}

type XmlResult struct {
    XMLName xml.Name `xml:"response"`
    Device  *Device
    User    *User
}

type Device struct {
    XMLName xml.Name `xml:"device"`
    Id      int      `xml:"id,attr"`
    Label   string   `xml:",innerxml"`
}

type User struct {
    XMLName  xml.Name `xml:"user"`
    Username string   `xml:"username"`
    Role     string   `xml:"role"`
    Age      int      `xml:"age,attr"`
}

但是使用 xml.Unmarshal不会产生预期的输出。但是如果我用一些元素包装结果并调整 XmlResponse结构如下:

<envelope>
  <error>Database Error</error>
</envelope>

对于正常响应为:

<envelope>
  <response>
    <device id="1">Test Device</device>
  </response>
</envelope>

结构为:

type XmlResponse struct {
    XMLName xml.Name   `xml:"envelope"`
    Error   *XmlError
    Result  *XmlResult
}

我可以得到预期的结果。

Go Playground中有示例代码.

有没有一种方法可以将 xml 解码为 XmlResponse具有不同的根元素名称而不换行?

更新:所有响应代码都是 200,因此我无法通过查看响应代码来区分错误和正常响应。

最佳答案

为了捕获 API 返回的错误,您通常应该检查响应代码,然后采取相应措施。
在您的情况下,应该返回一个 >500 的代码,表明存在服务器端错误。然后您可以尝试根据返回的错误消息格式解码响应正文。

如果那不是一个选项,您总是可以尝试解码到错误结构中,如果操作因错误而失败,您可以捕获它并解码到您的响应结构中。

但是你必须小心你捕捉到的错误,因为未能解码到错误类型并不自动意味着它是一个有效的响应类型。

关于xml.Unmarshall 多根 XML 在 Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59682284/

相关文章:

java - 将 dom4j 文档写入 xml 文件并转义 '\r\n\'

go - 如何在 echo 中使用自定义上下文正确测试处理程序?

Go: “no such file or directory” 但它存在

java - 删除xml文件中字符串前后不需要的字符串

c# - Xml 命名空间前缀规范器

xml - 在 Go 中编码(marshal) XML 时如何保留标记的 namespace url

Go:为新旧变量分配多个返回值函数

go - 使用 golang 以与 openssl genrsa 相同的方式获取 RSA key

mysql - postgres - 修改 xml(MySql UpdateXml 替代)

java - 将 CData 添加到格式不正确的 XML 元素