0

I am looking for a XSD to validate if a XML containing file elements with many payments have the same currency.

Example:

<Payments>
    <Payment>
        <PaymentDate>2020-09-28</PaymentDate>
        <Amount>11</Amount>
        <Currency>USD</Currency>
    </Payment>
    <Payment>
        <PaymentDate>2020-09-27</PaymentDate>
        <Amount>19</Amount>
        <Currency>USD</Currency>
    </Payment>
    <Payment>
        <PaymentDate>2020-09-27</PaymentDate>
        <Amount>12</Amount>
        <Currency>USD</Currency>
    </Payment>
</Payments>

The upper XML should be considered as valid because all <Currency> elements contain the same currency information.

However, the following XML should not be valid as it contains at least one payment with different currency information:

    <Payments>
        <Payment>
            <PaymentDate>2020-09-28</PaymentDate>
            <Amount>11</Amount>
            <Currency>USD</Currency>
        </Payment>
        <Payment>
            <PaymentDate>2020-09-27</PaymentDate>
            <Amount>19</Amount>
            <Currency>EUR</Currency>
        </Payment>
        <Payment>
            <PaymentDate>2020-09-27</PaymentDate>
            <Amount>12</Amount>
            <Currency>USD</Currency>
        </Payment>
    </Payments>

What should I do for my XSD? Thanks!

Filipe Santos
  • 61
  • 2
  • 9

2 Answers2

0

This needs XSD 1.1 with assertions:

<xs:assert test="count(distinct-values(.//Currency)) = 1"/>

I don't think there's any way to do it with XSD 1.0.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • I came up with something like this, too. But it was rejected at any place (I created a MCVE). It seems to be syntactically correct, but I couldn't fit it in a complete scenario with the XSD-1.1 `hu.unideb.inf.validator.SchemaValidator` validator. – zx485 Sep 28 '20 at 22:34
0

Just to provide a MCVE (This is not to be considered an answer):

<?xml version="1.0" encoding="utf-8"?>
<xs:schema version="1.1" xmlns:xs="http://www.w3.org/2001/XMLSchema"  elementFormDefault="unqualified">

  <xs:element name="Payments">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Payment" maxOccurs="unbounded">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="PaymentDate" />
                <xs:element name="Amount" />
                <xs:element name="Currency" />
              </xs:sequence>
            </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:assert test="count(distinct-values(Payment/Currency)) = 1" />
    </xs:complexType>
  </xs:element>
  
</xs:schema>

And it doesn't work.
This is only provided as a base for others to work on this.

zx485
  • 28,498
  • 28
  • 50
  • 59