Jump to content

Allow child nodes based on its attribute value


Guest Prashant P

Recommended Posts

Guest Prashant P

Requirement:Node "x" contains one or more Node "x" itselfNode "x" should be allowed as a child element of Node "x" if and only if attribute "a1" or "a2" is set to true.My current scheme definition for node "x" is as follows

<xs:element name="x">	<xs:complexType>	  <xs:sequence>		<xs:element ref="child1" minOccurs="0" maxOccurs="1"/>		<xs:element ref="x" minOccurs="0" maxOccurs="unbounded"/>	  </xs:sequence>	</xs:complexType></xs:element>

Furthermore, is it possible that the following rules can be enforced on the xml file?

<x>	<x a1="true">First Child</x> <!-this node shouldn't contain any child elements - -></x><x>	<x a2="true">First Child</x> <!-this node shouldn't contain any child elements - -></x><x>	<x a1="true">First Child</x> <!-this node shouldn't contain any child elements - ->	<x a1="true">Second Child</x> <!-this node shouldn't contain any child elements - -></x>

Link to comment
Share on other sites

This is not possible with Schema 1.0. Schema 1.1 has this as it's main goal. See XSDL 1.1's intro for details.As a workaround, you may define the a1 and a2 attributes as elements instead, that does (not) have any child elements.

Link to comment
Share on other sites

Today I repeated part of Robert Richards (2006) "Pro PHP XML and Web Services." He gives some very sound rules regarding the use of attributes in XML that I will repeat here. When considering whether you should use an attribute or whether it should be a child element, you have a few facts to consider. If you can answer "yes" to any of the following questions, then you should use an element rather than an attribute.

  1. Could multiple values apply to an element?
  2. Is a DTD requiring for the attribute being used?
  3. Is the data essential to the document and not just an instruction to an application?
  4. Is the value complex data or difficult to understand?
  5. Does the value need to be extensible for potential future use?

If the questions aren't applicable, then it comes down to personal preferences. One point to always remember, is that the document should end up being understood by a human and not just for for electronic processing. With this in mind, you have to ask yourself which of the following is easier to understand. This is the first choice:<Car make='ford' color='black' year='1990' model='Escort' />and this is the second choice:<Car>

<make>ford</make><color>black</color><year>1990</year><model>Escort</model>

</Car> So after reading this, you may conclude that using elements (with children) is the best solution.An XML schema is an XML document and should as such be well-formed.

As a workaround, you may define the a1 and a2 attributes as elements instead, that does (not) have any child elements.
Agree.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...