Reputation: 13643
I'm writing an XSD for a rather complex XML file format. At many points, the XML can either contain an actual literal value or a script yielding the value. (Think Excel: 42
vs. =21+21
)
For example, to specify a size, it should be valid to write either of the following:
<size>42</size>
<size><script>2*21</script></size>
My first thought was using <choice>
to allow either an int or a script within the size
element. However, then I would have to give the string element a name, leading to a clumsy syntax like <size><value>42</value></size>
. Since literals will be used far more often than scripts, I don't want to bloat their syntax.
Any ideas how to express the initial syntax in XSD?
Upvotes: 5
Views: 3069
Reputation: 163262
In XSD 1.0, if you don't want to change the design of the XML instance, your only real option is to declare the content model to be mixed content.
In XSD 1.1, you can declare it as mixed content and then use an assertion to say that the element must either have an element child or a text node child, but not both.
Upvotes: 2
Reputation: 2897
I think there are two decent options.
<size>
in either case. Instead, you could set a 'type' attribute on your size element, indicating to a consumer whether it's a literal or script. To choose between these options, you would put yourself in the shoes of the consumer app, and decide how it would most likely want to get this data. In general, I think option one is best if the primary consumer is a developer parsing the XML as a one-off integration task (because both the output and the XSD are more terse, and in my opinion more readable); option two is probably better if you see a XML tool consuming your schema and therefore it may have an easier time doing something special if there are concrete elements to parse out. Ultimately though I'm just guessing what your use-case is...
Upvotes: 5