gpt4 book ai didi

XML 架构 : how to declare complexType that has either attribute or child with the same name

转载 作者:行者123 更新时间:2023-12-04 05:12:05 25 4
gpt4 key购买 nike

对于我的 XSD 模式,我希望元素具有一个必需的附加值,该值可以在元素的属性或其子元素中指定。

示例:应允许以下元素:

<flower color="red" />

或:

<flower><color>red</color></flower>

但是下面的元素应该是无效的:

<flower />

和:

<flower></flower>

和:

<flower color="red"><color>blue</color></flower>

而且我完全不知道如何做到这一点。

最佳答案

在 XSD 1.0 中,您唯一的选择是用散文形式记录约束。 (例如,在模式的模式中,它对元素声明有类似的约束。)

在 XSD 1.1 中,您可以使用断言来记录和强制约束。稍微修改 Petru Gardea 建议的模式文档,我们有:

<xs:schema targetNamespace="http://example.com/colors" 
xmlns:tns="http://example.com/colors"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:simpleType name="flowerColor">
<xs:restriction base="xs:normalizedString">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>

<xs:complexType name="flowerVariantC">
<xs:sequence>
<xs:element name="color"
type="tns:flowerColor"
minOccurs="0"/>
</xs:sequence>
<xs:attribute name="color"
type="tns:flowerColor"
use="optional"/>
<xs:assert test="(./tns:color or ./@color)
and not(./tns:color and ./@color)"/>
</xs:complexType>

<xs:element name="flower" type="tns:flowerVariantC"/>
<xs:element name="test"/>

</xs:schema>

给定刚刚显示的模式文档和以下实例,Saxon 将第一个和第四个花元素视为无效而拒绝。

<test xmlns="http://example.com/colors"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://example.com/colors colors.xsd">
<flower/>
<flower color="red"/>
<flower><color>blue</color></flower>
<flower color="blue"><color>blue</color></flower>
</test>

(也就是说,我的直觉是反对这种不必要的复杂设计:选择将颜色作为属性,或者选择将其作为子项。事实上,每一个都是合理的设计并不 意味着允许它在文档中变化是一个合理的设计。)

关于XML 架构 : how to declare complexType that has either attribute or child with the same name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com