Reputation: 28869
At the XSD level, can I define an element requirement based on presence of another element in the document?
For example, I want to require the element <firstname />
be provided whenever the <id />
element is also present, otherwise first name is optional.
If this cannot be enforced at the XSD level, then should I make both elements optional and enforce the requirement through a different level of checking?
Options welcome.
Upvotes: 1
Views: 357
Reputation: 52858
Here's an example of this being done in a DTD. (Note: The test instances were validated using oXygen XML Editor (which is using Xerces).)
DTD (test.dtd)
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT user ((firstname?|(firstname,id)),lastname)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT id (#PCDATA)>
Here are some example XML instances (valid and invalid):
Valid
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE user SYSTEM "test.dtd">
<user>
<firstname/>
<id/>
<lastname/>
</user>
Invalid
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE user SYSTEM "test.dtd">
<user>
<id/>
<lastname/>
</user>
Valid
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE user SYSTEM "test.dtd">
<user>
<firstname/>
<lastname/>
</user>
Upvotes: 1
Reputation: 2741
This cannot be enforced at the XSD level.
Making both elements optional and enforcing the requirement at a different level in the application architecture sounds like a good option to me.
Upvotes: 1