Reputation: 68
Is it possible to validate the following XML, where the parent's child name is it's attribute "name":
<root>
<parent name="foo">
<foo/>
</parent>
<parent name="bar">
<bar/>
</parent>
<parent name="abc">
<xyz/> <!-- invalid -->
</parent>
</root>
The XSD, as per request:
<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="parentType">
<xsd:sequence>
<!-- TODO: enforce element name same as it's parent's attribute "name" -->
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required"/>
</xsd:complexType>
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="parent" type="parentType"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
The "TODO" is where I'm stumped. Thanks in advance for any help!
Upvotes: 1
Views: 153
Reputation: 25054
Is this an exercise in seeing what can go wrong when you violate the rule "Don't Repeat Yourself" in XML?
Upvotes: 0
Reputation: 111756
In XSD 1.0, you cannot specify such a constraint directly, but you could specify it using Schematron or check it at the application level.
In XSD 1.1, you could use xsd:assert
:
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema elementFormDefault="qualified"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="parentType">
<xsd:sequence>
<xsd:any processContents="lax" minOccurs="1" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:assert test="@name = local-name(*[1])"/>
</xsd:complexType>
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="parent" type="parentType" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Upvotes: 1