As an XML "noob" I have discovered the importance of element order when creating an XML stream/file that is validated against a DTD. Is it possible to define a DTD that is not order dependent on elements ? If, so please provide syntactic example.
Asked
Active
Viewed 8,626 times
11
-
Do you want a DTD only or is XML Schema an option? – Apr 13 '11 at 02:28
-
@Bavarious. Sorry, may be my question is poorly worded. I have a DTD internally defined in an XML "document". No Schema. – angryITguy Apr 13 '11 at 02:31
-
possible duplicate of [XML, DTD: how to make the order not important](http://stackoverflow.com/questions/4744507/xml-dtd-how-to-make-the-order-not-important) – Apr 13 '11 at 02:32
-
@Bavarious. I think You're right.... – angryITguy Apr 13 '11 at 02:34
2 Answers
22
You use or (a vertical pipe) and repeat (an asterisk:)
<!ELEMENT eltype1 ( eltype2 | eltype3)*>
This means eltype1
can contain any number of repetitions of eltype2
or eltype3
.

Ernest Friedman-Hill
- 80,601
- 10
- 150
- 186
-
1I just tested your solution and it's more concise than that found here http://stackoverflow.com/questions/4744507/xml-dtd-how-to-make-the-order-not-important (via Bavarious). The only drawback is that it does not enforce the existence of the pair but rather either one in any order :( – angryITguy Apr 13 '11 at 02:36
14
The only issue with the currently accepted answer is that it doesn't force only one of each element in any order. For example, you could have 2 eltype2
elements and no eltype3
elements.
If you need to be sure that both elements are present and that each occurs only one time, this is a more precise element declaration:
<!ELEMENT eltype1 ((eltype2, eltype3)|(eltype3, eltype2))>
Example in an internal subset:
<!DOCTYPE eltype1 [
<!ELEMENT eltype1 ((eltype2, eltype3)|(eltype3, eltype2))>
<!ELEMENT eltype2 (#PCDATA)>
<!ELEMENT eltype3 (#PCDATA)>
]>
<eltype1>
<eltype3>element three</eltype3>
<eltype2>element two</eltype2>
</eltype1>

Daniel Haley
- 51,389
- 6
- 69
- 95
-
It seems DTD is bad at this kind of thing. I shudder to think of the expression you'd need if you wanted something like "elem1 is required (exactly once), elem2 is optional (at most once), elem3 is repeatable and required (at least once), and elem4 is is repeatable and optional" and we want all that in any order – Mark VY Jul 26 '22 at 18:44
-
1@MarkVY - Yeah when it gets super complex like that, I prefer to do that level of checking with another technology (schematron, xslt/xquery, python script, etc.) and leave the DTD (or more often XML Schema these days) a little loose. Either that or rethink the data architecture and try to eliminate/reduce the need for such complexity. – Daniel Haley Jul 26 '22 at 18:50
-