Pregunta

I have an XML file. I am trying to generate xsd schema file. My xml file:

<?xml version="1.0" encoding="UTF-8"?>
<recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="sample.xsd" id="62378">

  <title>Beans On Toast</title>
  <ingredients>
     <item quantity="1" unit="slice">bread</item>
     <item quantity="1" unit="can">bakedbeans</item>        
  </ingredients> 
</recipe>

My schema file is:

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

<xs:element name="recipe" type="recipeType"/>
<xs:complexType name="recipeType">
    <xs:sequence>
        <xs:element name="title" type="xs:string"/>
        <xs:element name="ingredients" type="ingredientsType"/>           
    </xs:sequence>
    <xs:attribute name="id" type="xs:integer"/>
</xs:complexType>

<xs:complexType name="ingredientsType">
    <xs:sequence>
        <xs:element name="item" type="itemType"/>
    </xs:sequence>    
</xs:complexType>          

<xs:complexType name="itemType">
    <xs:attribute name="quantity" type="xs:integer"/>
    <xs:attribute name="unit" type="xs:string"/>
</xs:complexType>    
</xs:schema>

I am getting error while validating. I know the reason. Because I have failed to define element item type = xs:string because I have to write complexType("itemType") for attributes. Can anyone please solve this issue?

¿Fue útil?

Solución

If you need attributes, you have to use a complexType. But if you also need simple content, then you can define your complexType as containing simpleContent and extend it with attributes using a base simple type

In your case, you could do something like this:

<xs:complexType name="itemType">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute name="quantity" type="xs:integer"/>
            <xs:attribute name="unit" type="xs:string"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

This will allow:

<item quantity="1" unit="slice">bread</item>

You still need to allow more than one <item> element inside ingredientsType. If you can have unlimited items, you can use:

<xs:complexType name="ingredientsType">
    <xs:sequence>
        <xs:element name="item" type="itemType" maxOccurs="unbounded" />
    </xs:sequence>    
</xs:complexType>

Otros consejos

Try declaring itemType as mixed (use mixed='true' on the complex type definition).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top