vishwas 115
vishwas 115

Reputation: 23

How to prevent empty element in XSD while requiring an attribute

I am validating an XML document with the below XSD, and I want to ensure that the value of reportPath is not empty.

Here is my current XSD..

    <xs:element name="reportPath">
      <xs:complexType>
        <xs:simpleContent>
          <xs:extension base="xs:string">
            <xs:attribute name="Name" type="xs:string" use="required" />
          </xs:extension>
        </xs:simpleContent>
      </xs:complexType>
    </xs:element>

Example:

I want my XSD validator to return false when no value is present in reportPath

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns="ReportAutomation"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="ReportAutomation CommandLine.xsd">
  <templatePath Name="sourcePath">C:\Users\vm821231 Documents\sdtwetrwer.docx</templatePath>
  <reportPath Name="destPath"></reportPath>
  <filter Name="filters">ProjectName=PAL Controller;FolderName=Regression 2 Protocols\!03 Controller 3: Pump Operation;</filter>
</configuration>

Upvotes: 1

Views: 2653

Answers (1)

kjhughes
kjhughes

Reputation: 111491

You can restrict the length to be at least 1 character via <xs:minLength value="1"/> (as Ken White mentioned in the comments).

Here's how it all fits together for your XML sample, including how to use xs:restriction while concurrently requiring the Name attribute

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:ra="ReportAutomation"
           targetNamespace="ReportAutomation"
           elementFormDefault="qualified">

  <xs:element name="configuration">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="templatePath" type="ra:namedNonEmptyType"/>
        <xs:element name="reportPath" type="ra:namedNonEmptyType"/>
        <xs:element name="filter" type="ra:namedNonEmptyType"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="namedNonEmptyType">
    <xs:simpleContent>
      <xs:extension base="ra:nonEmptyString">
        <xs:attribute name="Name" use="required"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>

  <xs:simpleType name="nonEmptyString">
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
    </xs:restriction>
  </xs:simpleType>

</xs:schema>

Upvotes: 4

Related Questions