Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating attribute uniqueness with XSD across XML document

I'm trying to validate the uniquess of an attribute across all elements that exist in an XML document.

Example XML:

<exampleXml>
  <a id="1"/>
  <a id="2">
    <b id="1"/>
  </a>
</exampleXml>

My XSD schema:

<xs:schema elementFormDefault="qualified">
  <xs:element name="exampleXml">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="unbounded" name="a">
          <xs:complexType>
            <xs:complexContent>
              <xs:extension base="baseRuleType">
                <xs:sequence>
                  <xs:element minOccurs="0" maxOccurs="1" name="b">
                    <xs:complexType>
                      <xs:complexContent>
                        <xs:extension base="baseRuleType"/>
                      </xs:complexContent>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
              </xs:extension>
            </xs:complexContent>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
    <xs:unique name="duplicateIdsForbidden">
      <xs:selector xpath="//"/>
      <xs:field xpath="@id"/>
    </xs:unique>
  </xs:element>
  <xs:complexType name="baseRuleType">
    <xs:attribute name="id" use="optional"/>
  </xs:complexType>
</xs:schema>

The xpath is the issue here. I want to match every element under root but the selector xpath above returns:

Element '{http://www.w3.org/2001/XMLSchema}selector', attribute 'xpath': 
The XPath expression '//' could not be compiled

I can change the xpath to "*" but that will only validate the id attribute on the elements that are direct decendants of the root.

I am validating this with lib_xml in PHP using DOMDocument::schemaValidate(). Any help greatly appreciated.

like image 537
Peter Chapman Avatar asked Jul 15 '11 11:07

Peter Chapman


People also ask

Can we validate XML documents against so schema?

You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.

How can XML documents be validated?

To validate the XML in the DOM, you can validate the XML as it is loaded into the DOM by passing a schema-validating XmlReader to the Load method of the XmlDocument class, or validate a previously unvalidated XML document in the DOM using the Validate method of the XmlDocument class.


1 Answers

Use <xs:selector xpath=".//*"/>.

like image 118
Martin Honnen Avatar answered Oct 17 '22 07:10

Martin Honnen