Question

Let's say I have a many-to-many relationship between customers and retailers. One Customer can have multiple retailers and one retailer can have multiple customers.

So, in XSD, I'd write something like this:

<xs:schema xmlns="http://mynamespace" 
            targetNamespace="http://mynamespace" 
            xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="shop">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element ref="retailer" />
        <xs:element ref="customer" />
      </xs:choice>
    </xs:complexType>
  </xs:element>
  <xs:element name="retailer">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="customer" maxOccurs="unbounded" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="customer">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="retailer" maxOccurs="unbounded" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

The problem here is when I want to insert a retailer R1, then I'd associate a customer C1 to him, which then gets retailer R1 associated again (R1 -> C1 -> R1) - resulting in a fine recursive loop.

So how should one go about those cases?

EDIT

So what I have in mind is something similar to how RDBMs handle n-m-relations. I have two tables (customer and retailer) and a third table customer_retailer, which only contains the primary keys of the other two tables as unique foreign key-pairs.

In XSD, what I can imagine is that I let users create retailers and customers independently from another, and inside each element-instance reference only a key to the specific element. That is, I do not do this:

<retailer>
  <customer>
    <retailer>
      ...
    </retailer>
  </customer>
</retailer>

But this:

<retailer id="r1">
  <customer ref_id="c1" />
  <customer ref_id="c2" />
</retailer>
<customer id="c1">
  <retailer ref_id="r1" />
  <retailer ref_id="r2" />
</customer>
...
Was it helpful?

Solution

This question doesn't seem to have anything to do with XSD. You can certainly hold both directions of the relationship in your XML document if you want (it's up to you), but if you do, then it's your responsibility when you write code to update the structure to keep the two directions of the relationship in sync, and to avoid infinite loops. That's hardly a difficult problem, but the details depend entirely on how you are implementing your update logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top