문제

I have an XML document with (basically) looks like this:

...
<param>
    <key>age</key>
    <value>10</value>
</param>
<param>
    <key>smart</key>
    <value>true</value>
</param>
...

I would like to constrain available values based on the parameter key, e.g. age should be an integer in the [0, 150] and smart should be either true or false.

Now, if the XML was different (e.g. as in the example below), it would be very simple:

...
<age>10</age>
<smart>true</smart>
...

However, the XML structure will not change at this point and I'm not sure it should. Is there a way to implement these kinds of constraints with the current XML structure and if so, how?

UPDATE:

Judging by the (complete absence of) feedback, I would say it is likely that this is not possible using XSD. Can someone confirm?

도움이 되었습니까?

해결책

Seems like you would practically need a definition that looks something like this:

  <!-- This is an INVALID example -->
  <xs:element name="param">
    <xs:complexType>
      <xs:choice>
        <xs:sequence>
          <xs:element name="key" type="xs:string" fixed="age" />
          <xs:element name="value" type="xs:decimal" />
        </xs:sequence>
        <xs:sequence>
          <xs:element name="key" type="xs:string" fixed="smart" />
          <xs:element name="value" type="xs:boolean" />
        </xs:sequence>
      </xs:choice>
    </xs:complexType>
  </xs:element>

Unfortunately such piece of code results in invalid XML Schema file.

Although the syntax is correct, the semantics violate the schema rules. Elements with the same name and in the same scope must have the same type. In this case it especially means that all the <value> elements that are children of <param> elements must have same type.

Formally this is Schema Component Constraint: Element Declarations Consistent. See also the following schema component constraint; generally you cannot make a element type dependant on some other values in the document or on any information about the items in the remainder of the sequence.

Update

I totally forgot this but you should be able to get the constraints you want if you specify the desired type in the instance document instead of defining it purely in the schema. This can be done by adding the xsi:type attribute to <value> elements.

Example

<param>
    <key>age</key>
    <value xsi:type="xs:decimal">10</value>
</param>
<param>
    <key>smart</key>
    <value xsi:type="xs:boolean">true</value>
</param>

Of course this is slightly inconvenient, because it requires changing the XML generation process. Also it doesn't automatically provide any guarantee that <key> and the defined xsi:type are a matching pair.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top