XML Schema: how can i only create a parent element if the child element exists?

Looking at the following XML Schema:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="root">
  <xs:complexType>
    <xs:sequence>
        <xs:element name="parent" minOccurs='0'>
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="child" type="xs:string" minOccurs='0' maxOccurs='unbounded'/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>

It will give me the following XML output if no element child exists:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <parent />
</root>

And the following XML output if one element child named "child_1" exists:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <parent>
    <child>child_1</child>
  </parent>
</root>

However, I only want the parent element to exist in the case where at least one child exist. Meaning in the first case I want the following XML output with the <parent /> element missing:

<?xml version="1.0" encoding="utf-8"?>
<root>
</root>

How can I modify my XML Schema to achieve that? I am sure this question or a very similar one has been asked already, but I am unable to find it. I am probably searching for the wrong keywords.



Read more here: https://stackoverflow.com/questions/66335506/xml-schema-how-can-i-only-create-a-parent-element-if-the-child-element-exists

Content Attribution

This content was originally published by hakuna your tatas at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: