【问题标题】:Ensure child element cannot exist without parent Using Xsd使用 Xsd 确保子元素不能在没有父元素的情况下存在
【发布时间】:2012-08-17 07:08:27
【问题描述】:

我在尝试在 xsd 中进行此架构验证时遇到问题。

有效案例

<root>
   <groups>
      <group/>
   </groups>
</root>

Valid case
<root>
<groups/>
</root>

无效的情况

<root>
  <group/>
</root>

如何通过xsd保证某个特定子元素只能存在于某个父元素下,不能单独存在于xml中?

在这个例如 group 不能单独存在,但是当groups是parent时可以存在...

有人回答说不要使组元素全局化,即包含在组元素中......

但也有可能是这样, 其中 group 不是父母的直接孩子。 例如 有效案例

<groups>
<class>
   <group>
</class>
</groups>

在这种情况下应该做什么......因为类也需要引用组......

【问题讨论】:

  • 等待回复伙计们..m卡在这个..

标签: xsd


【解决方案1】:

根据您的问题,在我看来,您希望班级和小组可以互换。为此,您想使用递归模式元素,就像这样......

<xsd:element name="Groups">
    <xsd:complexType>
        <xsd:complexContent>
            <xsd:extension base="BranchType"/>
        </xsd:complexContent>
    </xsd:complexType>
</xsd:element>

<xsd:complexType name="BranchType">
    <xsd:sequence>
        <xsd:choice minOccurs="0" maxOccurs="unbounded">
            <xsd:element name="Class" type="BranchType" minOccurs="0" maxOccurs="1"/>
            <xsd:element name="Group" minOccurs="0" maxOccurs="1"/>
        </xsd:choice>
    </xsd:sequence>
</xsd:complexType>

我们基本上定义了一个 BranchType,它可以包含 Group 元素或其自身的任意组合(通过 Class 元素)。然后我们将顶级 Groups 定义为 BranchType 类型。我使用选择序列,以便 Class 和 Group 元素可以以任意顺序、任意次数出现在任何嵌套级别。

【讨论】:

    【解决方案2】:

    当您不希望元素单独显示时,必须在定义其父级的复杂类型中声明它。

    以下是由工具生成的简单“修复”;学习时,它可能是快速启动 XSD 的好方法,至少可以正确地使用语法...

    更新:如果您不断添加内容,则需要更新架构。如果元素不是全局元素,那么解决方案是相同的:在其父元素中定义。如果内容模型相同,则将其定义为全局类型,并在元素的定义中引用它(在这种情况下,它将代替 anyType)。

    <?xml version="1.0" encoding="utf-8"?>
    <!--XML Schema generated by QTAssistant/XML Schema Refactoring (XSR) Module (http://www.paschidev.com)-->
    <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="root">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="groups">
              <xs:complexType>
                <xs:sequence minOccurs="0">
                  <xs:element name="group" type="xs:anyType" />
                </xs:sequence>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="groups">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="class">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="group" type="xs:anyType" />
                </xs:sequence>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 2019-02-28
      • 1970-01-01
      • 2021-06-18
      • 2020-09-04
      相关资源
      最近更新 更多