Question

I have a mighty weird XML structure that I need to validate. At the same time I have to accept that I am not allowed to modify anything regarding its structure for political reasons.

I've managed to validate most of it by defining an idiotically overcomplex Schema. However a certain part of the XML seems almost impossible to validate with an XSD. Here is the problematic snippet:

<booktitles>
    <author>Some Author</author>
    <title>Title 1</title>
    <year>1666</year>
    <title>Title 2</title>
    <year>1919</year>
</booktitles>

So every booktitles entry contains exactly 1 author and a variable amount of title - year pairs.

So without modifying the XML structure (yes, I do realise how idiotic this sounds) is it possible to define an XSD which would validate/enforce it?

PS: I also have the possibility of using JaxB for the validation.

Was it helpful?

Solution

Try this:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="booktitles">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="author"/>
        <xs:sequence maxOccurs="unbounded">
          <xs:element ref="title"/>
          <xs:element ref="year"/>
        </xs:sequence>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="author" type="xs:string"/>
  <xs:element name="title" type="xs:string"/>
  <xs:element name="year" type="xs:string"/>
</xs:schema>

Courtesy of trang, from this

<!ELEMENT   booktitles
            (author, (title, year)+)
            >

<!ELEMENT   author
            (#PCDATA)
            >

<!ELEMENT   title
            (#PCDATA)
            >

<!ELEMENT   year
            (#PCDATA)
            >
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top