0

是否可以在 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>

我可以使用选择器/字段以某种方式排除空属性吗?

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

4

1 回答 1

1

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

XSD 往往有点家长式,因为它只允许您描述 XSD 设计者认为是良好实践的设计,我想 XSD 的设计者会告诉您,您应该在这里省略该属性而不是让它出现具有空值。

于 2021-07-05T16:44:03.940 回答