简体   繁体   中英

XML schema to validate parent, child nodes

Can you use XML schema to assert that a specific element conforms to a value of another element? In the example below I want to ensure that each node name who has a parent element, has a valid parent?

<doc>
  <entry>
    <Name>A</Name>
  </entry>
  <entry> 
    <Name>A1</Name>
    <Parent>A </Parent> <!-- valid parent defined above -->
  </entry>
  <entry>
    <Name>C1</Name>
    <Parent>C</Parent> <!-- this should fail; no entry node that is C -->
  </entry>
</doc>

The problem you described can be solved using this XSD:

<?xml version="1.0" encoding="utf-8"?>
<!--XML Schema generated by QTAssistant/XML Schema Refactoring (XSR) Module (http://www.paschidev.com)-->
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element maxOccurs="unbounded" name="entry">
                    <xsd:complexType>
                        <xsd:sequence>
                            <xsd:element name="Name">
                                <xsd:simpleType>
                                    <xsd:restriction base="xsd:string">
                                        <xsd:whiteSpace value="collapse"/>
                                    </xsd:restriction>
                                </xsd:simpleType>
                            </xsd:element>
                            <xsd:element minOccurs="0" name="Parent">
                                <xsd:simpleType>
                                    <xsd:restriction base="xsd:string">
                                        <xsd:whiteSpace value="collapse"/>
                                    </xsd:restriction>
                                </xsd:simpleType>                               
                            </xsd:element>
                        </xsd:sequence>
                    </xsd:complexType>
                </xsd:element>
            </xsd:sequence>
        </xsd:complexType>
        <xsd:key name="pk">
            <xsd:selector xpath="entry"/>
            <xsd:field xpath="Name"/>
        </xsd:key>
        <xsd:keyref name="fk" refer="pk">
            <xsd:selector xpath="entry"/>
            <xsd:field xpath="Parent"/>
        </xsd:keyref>
    </xsd:element>
</xsd:schema>

It looks like this:

在此处输入图片说明

It shows you how to implement what is a referential integrity requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM