152

I'm having difficulty searching for this. How would I define an element in an XML schema file for XML that looks like this:

<option value="test">sometext</option>

I can't figure out how to define an element that is of type xs:string and also has an attribute.

Here's what I've got so far:

<xs:element name="option">
    <xs:complexType>
        <xs:attribute name="value" type="xs:string" />
    </xs:complexType>
</xs:element>
james.garriss
  • 12,959
  • 7
  • 83
  • 96
Wilco
  • 32,754
  • 49
  • 128
  • 160

3 Answers3

185

Try

  <xs:element name="option" type="AttrElement" />

  <xs:complexType name="AttrElement">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="value" type="xs:string">
        </xs:attribute>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
David Norman
  • 19,396
  • 12
  • 64
  • 54
  • I am getting the following exception on trying your code - org.xml.sax.SAXParseException: src-resolve: Cannot r esolve the name 'AttrElement' to a(n) 'type definition' component. Why is that so? – Ashwin May 28 '12 at 10:07
  • 1
    If that is so, it is probably because your schema document has a target namespace and you will need to use a prefixed name to point to the type. (If the prefix `tns` is bound to the schema document's target namespace, you will use `type="tns:AttrElement"` to refer to the type.) – C. M. Sperberg-McQueen Jan 24 '13 at 09:00
  • @Ashwin you might need to reference the type with the type namespace (`type="tns:AtrElement"` if your default namespace of the XSD is xs not the targetNamespace of the document. Typically in that case `tns` is defined and used. – eckes Jul 27 '16 at 21:13
85

... or the inline equivalent:

<xs:element name="option">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="value" type="xs:string" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>
eckes
  • 10,103
  • 1
  • 59
  • 71
Julian H
  • 1,809
  • 17
  • 18
  • 16
    I find it really unintuitive to define `simpleContent` within a `complexType`. But then again it's XSD, where nothing seems really intuitive. Thanks nonetheless! :-) – flu Mar 08 '12 at 10:20
  • This will show an error for me in *IntelliJ* (*V12.1.3*): The value attribute is "not allowed". Using **complexContent** instead of **simpleContent** fixed it. – aZen May 11 '13 at 14:17
-1

I know it is not the same, but it works for me:

<xsd:element name="option">
    <xsd:complexType mixed="true">
        <xsd:attribute name="value" use="optional" type="xsd:string"/>
    </xsd:complexType>
</xsd:element>
eckes
  • 10,103
  • 1
  • 59
  • 71
Aitor
  • 21