Ram
Ram

Reputation: 23

Partial validation of XML using XSD

XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <employee_name>
    <name>Ram</name>
    <Prev_name>Kumar</Prev_name>
  </employee_name>
  <project ppact="BT">ODC</project>
  <team size="small">CMS</team>
</root>

XSD:

<?xml version="1.0"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="request">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="1" />
        <xs:element name="Prev_name" type="xs:string" minOccurs="1" maxOccurs="1" />
      </xs:sequence>
    </xs:complexType>
  </xs:element> 
</xs:schema>

I should validate the presence of 'name' and 'Prev_name' in my XML through XSD. I am not bothered about other tags.Whenever I pass an XML without those two tags or one of it, my XML validation should fail. If my XML has those 2 tags, then only XML validation should pass.

Upvotes: 0

Views: 1248

Answers (1)

Sprotty
Sprotty

Reputation: 5973

You can't really do validation on just a bit of the tree, the closest you can get is to provide rules for the employee_name. But you need to provide a set of rules for the root element (root).

enter image description here

<?xml version="1.0" encoding="utf-8" ?>
<!--Created with Liquid Studio 2018 - Developer Bundle (Educational) 16.0.0.7863 (https://www.liquid-technologies.com)-->
<xs:schema elementFormDefault="qualified"
           version="1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="employee_name">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name"
                            type="xs:string"
                            minOccurs="1"
                            maxOccurs="1" />
                <xs:element name="Prev_name"
                            type="xs:string"
                            minOccurs="1"
                            maxOccurs="1" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="root"
                type="xs:anyType" />
</xs:schema>

When the XML is validated against the schema the validator may create warnings for the 'unknown' types (shown with a yellow underline) but will create errors if name or Prev_name is missing from employee_name. It will also raise errors if extra elements to be added to employee_name.

enter image description here

Upvotes: 3

Related Questions