Epicurus
Epicurus

Reputation: 2133

XML Schema Question

Is it possible to define an XML Schema (XSD) to correctly describe a document such as the following?

<root>
    <str name="status">success</str>
    <str name="message">Your request has been processed successfuly.</str>
</root>

The problem might be that the <str> tags have an attribute (name) as well as string values. I would be grateful if anyone could come up with an XML Schema for this piece of XML, since I am kind of stuck at this point. My best attempt so far is shown below, but botice that the <str> element cannot have a type (such as xsd:string) in this context.

  <xs:element name="object">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="str" minOccurs="2" maxOccurs="2">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="productName" type="xs:string"/>
          </xs:sequence>
          <xs:attribute name="name" type="xs:string" use="required"/>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
  </xs:element>

Upvotes: 0

Views: 312

Answers (1)

fredw
fredw

Reputation: 1419

Your constraints are not entirely clear, so a number of schemas would validate the XML depending on how loose/tight you would want the validation to be. This example shows a schema that mandates exactly two elements inside the element and they must have a "name" attribute with the values "status" or "message".

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="str" type="StrType" minOccurs="2" maxOccurs="2"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="StrType">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="name" type="StrAttribute" use="required" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>

  <xs:simpleType name="StrAttribute">
    <xs:restriction base="xs:string">
      <xs:enumeration value="status"/>
      <xs:enumeration value="message"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

Of course, this would allow two elements both with the name attribute set to "message", or with "message" first, then status. I believe the schema cannot define a sequence containing two elements of the same name but different types which you would need if you required the validation to ensure that the first always contained "status" and the second one contained "message".

Upvotes: 1

Related Questions