You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenAPI 3.0中正确定义XML对象数组?

解决OpenAPI 3.0中XML员工数组响应的定义问题

你遇到的核心问题是没有正确定义数组类型的XML结构——原代码里的Employee属性被定义为单个对象而非数组,同时XML标签的命名也不符合预期。我帮你修正配置,让SwaggerHub生成和你需求一致的XML响应示例:

修正后的完整OpenAPI YAML代码

openapi: 3.0.0
info:
  title: General Document
  version: "1.0"
  contact:
    email: developer@email.com
  description: >
    # Introduction
    This document describes a list of API's available. \
paths:
  /employees:
    get:
      description: This will return employees information in JSON and XML formats
      responses:
        200:
          $ref: '#/components/responses/employeesAPI'
components:
  responses:
    employeesAPI:
      description: This will return information about employees
      content:
        application/xml:
          schema:
            $ref: '#/components/schemas/EmployeesInfo'
  schemas:
    Employee:
      type: object
      required:
        - EmpId
        - Name
        - Mobile
        - EmailId
      properties:
        EmpId:
          type: string
          example: "001"
          description: Employee id
        Name:
          type: string
          example: "Steven"
          description: Employee name
        Mobile:
          type: string
          example: "1-541-754-3010"
          description: Employee mobile
        EmailId:
          type: string
          example: "steven@yourcomany.com"
          description: Employee email
    EmployeesInfo:
      type: object
      required:
        - Employee
      properties:
        Employee:
          type: array
          items:
            $ref: '#/components/schemas/Employee'
          # 指定数组元素的XML标签为<Employee>
          xml:
            name: "Employee"
      # 指定根节点的XML标签为<Employees>
      xml:
        name: "Employees"
servers:
  - description: SwaggerHub API Auto Mocking
    url: https://virtserver.swaggerhub.com/name2200/test/1.0

关键修改说明

  • 将Employee属性改为数组类型:
    原代码里Employee是单个object,现在改成array类型并通过items引用Employee schema,这样才能表示多个员工对象的集合。
  • 配置XML标签命名:
    在EmployeesInfo的xml属性中设置name: "Employees",对应你需要的根节点<Employees>;在Employee数组属性的xml中设置name: "Employee",让数组中每个元素都被<Employee>标签包裹。
  • 优化示例值:
    我把示例值替换成了你提供的真实样例,这样SwaggerHub生成的响应示例会更贴近预期效果。

修改完成后,SwaggerHub会生成和你需求完全一致的XML响应:

<Employees>
  <Employee>
    <EmpId>001</EmpId>
    <Name>Steven</Name>
    <Mobile>1-541-754-3010</Mobile>
    <EmailId>steven@yourcomany.com</EmailId>
  </Employee>
  <Employee>
    <EmpId>002</EmpId>
    <Name>Mark</Name>
    <Mobile>1-551-754-3010</Mobile>
    <EmailId>mark@yourcomany.com</EmailId>
  </Employee>
</Employees>

内容的提问来源于stack exchange,提问作者Rabikatha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:05:13