How to limit a set of attributes in xsd

All Please suggest me to limit the following in the xsd scheme:

<root>
  <node action="action1" parameter="1" />
</root>

I need to specify the parameter attribute only if the action attribute is defined.

Thank,

+3
source share
2 answers

The W3C schema is not able to express conditionally necessary attributes.

Schematron is a great tool for verifying that documents adhere to custom validation scripts that require a conditional requirement.

You can define these attributes as optional in your schema, and then use Schematron to test it for these conditional rules.

+4
source

I created this xsd to try to solve the problem.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLSchema1"
    targetNamespace="http://tempuri.org/XMLSchema1.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema1.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema1.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:group name="populated">
    <xs:sequence >
      <xs:element name="node">
        <xs:complexType>
          <xs:attributeGroup ref="actionattrib" />
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:group>
  <xs:group name="unpopulated">
    <xs:sequence >
      <xs:element name="node">
        <xs:complexType>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:group>
  <xs:attributeGroup name ="actionattrib">
    <xs:attribute name="action1" type="xs:string" />
    <xs:attribute name="parameter" type="xs:int" />
  </xs:attributeGroup>
  <xs:element name="root">
    <xs:complexType>
      <xs:choice minOccurs ="0">
        <xs:group ref="populated" />
        <xs:group ref ="unpopulated" />
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

And the testing method:

    public static void Go()
    {
        string nameSpace = "http://tempuri.org/XMLSchema1.xsd";
        XmlSchemaSet schemas = new XmlSchemaSet();
        schemas.Add(nameSpace, "XMLSchema1.xsd");

        XDocument myDoc1 = new XDocument(
            new XElement(XName.Get("root", nameSpace),
                new XElement( XName.Get("node", nameSpace ))
                )
            );
        myDoc1.Validate(schemas, (o, e) => { Console.WriteLine(e.Message); });
    }

:

"http://tempuri.org/XMLSchema1.xsd: node" , . , , , , , , , - .

Mads. .

0

All Articles