xsd 中的可选 keyref?

Optional keyref in xsd?

是否可以在 xsd 中定义一个属性,使其可能有一个空值,但在有值时被检查以引用另一个元素?

<?xml version="1.0" encoding="UTF-8"?>
<TableStructure xmlns="tmp/TableStructure"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="tmp/TableStructure TableStructure.xsd">
  <Column name="a" />
  <Column name="b" />
  <Column name="c" />
  <Range name="r1" fromColumn="a" toColumn="b" /> <!-- works -->
  <Range name="r2" fromColumn="a" toColumn="" /> <!-- should work -->
  <Range name="r3" fromColumn="a" /> <!-- works -->
  <Range name="r4" fromColumn="" toColumn="c" /> <!-- should work -->
  <Range name="r5" fromColumn="foo" toColumn="bar" /> <!-- should not and does not work -->
</TableStructure>

我尝试了以下架构:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="tmp/TableStructure" elementFormDefault="qualified"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns="tmp/TableStructure"
            xmlns:ts="tmp/TableStructure">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace"
                schemaLocation='http://www.w3.org/2009/01/xml.xsd' />

    <xsd:element name="TableStructure">
        <xsd:complexType>
            <xsd:sequence minOccurs="1" maxOccurs="1">
                <xsd:element ref="Column" maxOccurs="unbounded" minOccurs="0" />
                <xsd:element ref="Range" maxOccurs="unbounded" minOccurs="0" />
            </xsd:sequence>
        </xsd:complexType>
        <xsd:key name="columnName-key">
            <xsd:selector xpath="./ts:Column" />
            <xsd:field xpath="@name" />
        </xsd:key>
        <xsd:keyref name="fromColumn-ref" refer="columnName-key">
            <xsd:selector xpath="./ts:Range" />
            <xsd:field xpath="@fromColumn" />
        </xsd:keyref>
        <xsd:keyref name="toColumn-ref" refer="columnName-key">
            <xsd:selector xpath="./ts:Range" />
            <xsd:field xpath="@toColumn" />
        </xsd:keyref>
    </xsd:element>

    <xsd:element name="Column">
        <xsd:complexType>
            <xsd:attribute name="name" type="xsd:string" use="required" />
        </xsd:complexType>
    </xsd:element>

    <xsd:element name="Range">
        <xsd:complexType>
            <xsd:attribute name="name" type="xsd:string" use="required" />
            <xsd:attribute name="fromColumn" use="optional" type="xsd:string" />
            <xsd:attribute name="toColumn" use="optional" type="xsd:string" />
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

我可以使用 selector/field 以某种方式排除空属性吗?

我正在尝试为现有文件创建架构,并且希望不必更改它们来删除空属性。

不,keyref 功能不允许您将值为零长度字符串的属性与其他属性区别对待。

XSD 有点家长作风,因为它只允许您描述 XSD 设计师认为好的设计,我想 [=14= 的设计师] 会告诉您应该在此处省略该属性,而不是让它以空值出现。