I am facing an issue with an XML Schema
. I would like to introduce elements
into another element
which has been defined to be recursive.
The above lines of code are meant to represent file and folders.
Here is the current code:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">
<xs:complexType name="folder_type">
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="folder" type="folder_type"></xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"></xs:attribute>
</xs:complexType>
<xs:element name="filefoldertree">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="folder" type="folder_type"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
For instance, the above XSD
code allows me to define the following XML
lines:
<filefoldertree xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file:/C:/Users/Hadi/Desktop/filefoldertree.xsd">
<folder name="a">
<folder name="b">
<folder name="c">
</folder>
</folder>
</folder>
<folder name="d">
</folder>
</filefoldertree>
Until there, this is a desirable behavior. However I would like to add a sequence of file
elements
, nested in the folder
one. For example, I am seeking for the following result:
<folder name="a">
<folder name="b">
<file attr1="x" attr2="y" attr3="z"></file>
<folder name="c">
<file attr1="x" attr2="y" attr3="z"></file>
</folder>
</folder>
</folder>
<folder name="d">
<file attr1="x" attr2="y" attr3="z"></file>
</folder>
<file attr1="x" attr2="y" attr3="z"></file>
Since folder
is a typed
element
, I cannot define a nested complextype
, however I need its recursive functionality.
How to modify the XSD
code in order to achieve the behavior illustrated by the code above?
Thank you for your answers.
答案 0 :(得分:2)
You can use xs:choice
in a recursive type declaration as follows:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="filefoldertree" type="FolderType"/>
<xs:complexType name="FolderType">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="folder" type="FolderType"/>
<xs:element name="file" type="FileType"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="FileType">
<xs:sequence/>
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
</xs:schema>
Note: You might want to name the top-level element folder
rather than the one-off, filefoldertree
.