首页 文章

XSD:将element的属性值约束为父属性的子字符串

提问于
浏览
0

考虑一下这段XML

<Parent id="MyParent1">
   <Child id="MyParent1.MyChild1"/>
</Parent>

<Parent id="MyParent2">
   <Child id="MyParent2.MyChild1"/>
   <Child id="MySillyIncorrectPrefix.MyChild2"/>
</Parent>

如何验证(可能使用XSD)其id包含父元素id作为前缀的子元素,以便:

<Child id="MyParent2.MyChild1"/> <!-- is valid -->
<Child id="MySillyIncorrectPrefix.MyChild2"/> <!-- is not valid -->

我没有绑定XSD版本1.0,所以我可以尝试使用XSD 1.1(和断言等功能),但我想知道:

  • 如何用xs:assertion或更合适的XSD 1.1特性表达上述约束 .

  • 如果可以利用该xsd在Java中构建验证器吗? "Xerces-J"是一个可行的解决方案吗?

在我对XSD 1.1的有限知识中,我想出了这个尝试:

<xs:element name="Child"> 
  <xs:complexType>
     <xs:attribute name="type" type="xs:String" />
     <xs:assert test="starts-with(@type,../@type)"/>
</xs:complexType> 
</xs:element>

它是否正确?有没有可以测试它的工具?更一般:有没有工具来帮助构建和测试这种XSD 1.1特色模式? (afaik Eclipse仅支持XSD 1.0)

2 回答

  • 2

    您所描述的内容在XSD 1.0中是不可行的 .

    在XSD 1.1中,您可以对父类型使用断言,要求每个子节点的id属性以父节点id属性的值开头 .

  • 0

    此架构应验证该示例(使用xsd 1.1断言)

    <?xml version="1.1" encoding="UTF-8"?>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/stackoverflow" xmlns:tns="http://www.example.org/stackoverflow" elementFormDefault="qualified">
    
        <complexType name="ParentType">
            <sequence>
                <element name="Child" type="tns:ChildType"
                    maxOccurs="unbounded" minOccurs="0">
                </element>
            </sequence>
            <attribute name="id" type="string"></attribute> 
        </complexType>
    
        <element name="Parent" type="tns:ParentType"></element>
    
        <complexType name="ChildType">
            <attribute name="id" type="string"></attribute>
            <assert test="starts-with(@id,../@id)"/>
        </complexType>
    
    </schema>
    

相关问题