How to define DTD without strict element order?
Asked Answered
A

2

11

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.

Also answered 13/4, 2011 at 2:24 Comment(4)
Do you want a DTD only or is XML Schema an option?Heartbreak
@Bavarious. Sorry, may be my question is poorly worded. I have a DTD internally defined in an XML "document". No Schema.Also
possible duplicate of XML, DTD: how to make the order not importantHeartbreak
@Bavarious. I think You're right....Also
R
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.

Ramon answered 13/4, 2011 at 2:30 Comment(1)
I just tested your solution and it's more concise than that found here #4745007 (via Bavarious). The only drawback is that it does not enforce the existence of the pair but rather either one in any order :(Also
O
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>
Omer answered 7/6, 2011 at 2:15 Comment(3)
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 orderInterlocutrix
@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.Omer
yeah, makes sense, probably best to loosen it in that caseInterlocutrix

© 2022 - 2024 — McMap. All rights reserved.