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

XSD验证问题:XML校验失败及optional元素使用咨询

问题原因

你遇到的报错The markup in the document following the root element must be well-formed,本质是XML语法规则要求:一个合法的XML文档只能有一个顶级根元素。你当前的XML同时存在<note>和<optional>两个根元素,违反了这个规则。

两种正确解决方案

方案1:调整XSD,将optional设为note的可选子元素

这是更贴合业务逻辑的方式,把optional作为note的可选内容。修改后的XSD如下:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="note">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="to" type="xs:string"/>
        <xs:element name="from" type="xs:string"/>
        <xs:element name="heading" type="xs:string"/>
        <!-- 通过minOccurs="0"标记为可选子元素 -->
        <xs:element name="optional" minOccurs="0">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:maxLength value="10"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

对应的合法XML(可选择包含或不包含optional):

<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <optional>hi</optional>
</note>

方案2:新增根元素包裹note和optional

如果需要保留XSD中两个全局元素的定义,需在XML中新增一个统一的根元素,并同步修改XSD添加该根元素的定义:

修改后的XSD

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="note">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="to" type="xs:string"/>
        <xs:element name="from" type="xs:string"/>
        <xs:element name="heading" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="optional">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:maxLength value="10"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
  <!-- 新增根元素root的定义 -->
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="note"/>
        <xs:element ref="optional"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

对应的合法XML

<?xml version="1.0"?>
<root>
  <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
  </note>
  <optional>hi</optional>
</root>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:05:34