使用自定义属性扩展XSD?

Jon*_*ley 3 xml xsd

有没有办法用自定义属性扩展XSD元素?

例如,我想在XSD中执行以下操作:

<xs:element name="myElement" type="xs:string" myCustomAttribute="true" />
Run Code Online (Sandbox Code Playgroud)

Jon*_*ley 6

使用自定义属性扩展XSD可以通过首先在您自己的命名空间中定义自定义属性来完成,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           targetNamespace="http://www.mycompany.com" 
           elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:attribute name="myAttribute" type="xs:boolean" default="true"/>
</xs:schema>
Run Code Online (Sandbox Code Playgroud)

在此命名空间中,定义了一个http://www.mycompany.com名为的属性myAttribute,其类型为xs:boolean.

接下来,在目标模式中使用此命名空间,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
           xmlns:mc="http://www.mycompany.com" 
           xsi:schemaLocation="http://www.mycompany.com ./doc.xsd" 
           elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="element1" mc:myAttribute="false"/>
</xs:schema>
Run Code Online (Sandbox Code Playgroud)

在此示例中,<schema>元素包括定义自定义命名空间(xmlns:mc="http://www.mycompany.com")的属性,以及自定义模式文件(xsi:schemaLocation="http://www.mycompany.com ./doc.xsd")的位置.

目标模式包含单个元素,"element1"并具有myAttribute上面定义的自定义属性,其值为"false".请注意,自定义属性的名称以自定义名称空间前缀为前缀.另请注意,如果使用无效类型的值(例如mc:myAttribute="invalid":),则会生成验证错误.

感谢@GhislainFourny和@kjhughes对此答案的帮助.