seal
seal

Reputation: 520

Check if attribute has some value via XSD

I have a XML like this:

...
<result name="Result" test="xpto" cat="2"/>
<result name="ExecuteTest" test="xpto"/>
<result name="Result" test="xpto" cat="1"/>
<result name="CloseTest" test="xpto"/>
...

and my current XSD is this:

<xs:element name="result" maxOccurs="unbounded" minOccurs="1">
  <xs:complexType mixed="true">
    <xs:attribute type="xs:string" name="name" use="required"/>
    <xs:attribute type="xs:string" name="test" use="required"/>
    <xs:attribute type="xs:string" name="cat" use="optional"/>
  </xs:complexType>
</xs:element>

I want to validate in my XSD file, if in my XML file the first element <result> have the the value="Result" and if have the attribute cat="...". It is possible?

Upvotes: 2

Views: 730

Answers (1)

kjhughes
kjhughes

Reputation: 111541

First off, XML cannot have multiple root elements, so wrap your result elements in a common single root element:

XML A

<results>
  <result name="Result" test="xpto" cat="2"/>
  <result name="ExecuteTest" test="xpto"/>
  <result name="Result" test="xpto" cat="1"/>
  <result name="CloseTest" test="xpto"/>
</results>

Secondly, it's poor XML design to use generic element names with name attributes like this. Instead, consider:

XML B

<results>
  <Result test="xpto" cat="2"/>
  <ExecuteTest test="xpto"/>
  <Result test="xpto" cat="1"/>
  <CloseTest test="xpto"/>
</results>

XSD possibilities:

Finally, decide on one of the above XML designs and whether you're going to use XSD 1.0 or 1.1:

  • XSD 1.0 cannot represent your constraint for XML A.

  • XSD 1.0 could represent for XML B that all Result elements must have (required or optional) cat attributes with fixed values of 2.

  • XSD 1.1 could represent your constraint for XML A with Conditional Type Assignment, but would also need assertions to make a statement about positioning.

  • XSD 1.1 could use assertions alone for XML A or XML B.

Upvotes: 1

Related Questions