-->

XSD for varying element names

2020-04-21 05:26发布

问题:

I want to form an xsd schema for an XMl whose elements will range from z1-zx. Is it possible to define this in the xml schema without having to write out declare each of the elements.

Please see below:

<?xml version="1.0"?>
<Zones>
    <Z1>Asset00</Z1>
    <Z2>Asset00</Z2>
</Zones>

I want the zones to be able to go upto Zxxx without having to declare each and every one in the XSD, is it possible to do this?

Please note that I wouldn't be able to change the structure of the xml, as I am using this for another software which can only take this format.

回答1:

XSD 1.0

The best you can do in XSD 1.0 is allow any elements under Zones:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Zones">
    <xs:complexType>
      <xs:sequence>
        <xs:any processContents="skip" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
   </xs:element>
</xs:schema>

XSD 1.1

In XSD 1.1 you can go further and constrain the names of the children of Zones to start with Z:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  vc:minVersion="1.1">
  <xs:element name="Zones">
    <xs:complexType>
      <xs:sequence>
        <xs:any processContents="skip" maxOccurs="unbounded"/>
      </xs:sequence>
      <xs:assert test="every $e in * satisfies starts-with(local-name($e), 'Z')"/>
    </xs:complexType>
   </xs:element>
</xs:schema>

You could go even further and require that the string after the Z prefix be a number and probably even impose a sorted constraint as well, but this should get you pointed in the right direction.