Search code examples
xmlxsdjibx

How to add an attribute to the element in XSD


I'm using jibx to create a xml. the requirement i have is to get Xml as below

<report>
  <info>
   <meta name="acntNo">11111111</meta> 
   <meta name="location">USA</meta> 
   <meta name="Id">2222222222</meta> 
  </info>
</report>

My Question is how to add name attribute to the complexElement meta. I'll get the values of name attribute and meta text from java code.

I tried using

<xsd:complexType name="CareInfoType">
    <xsd:sequence>
        <!--  root of the meta -->
        <xsd:element name="meta" type="qdx:CareMetaInfo" minOccurs="1" maxOccurs="3">
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="CareMetaInfo">
    <xsd:attribute name="name" type="xsd:string" ></xsd:attribute>
</xsd:complexType>

Thanks in advance


Solution

  • You should use xsd:simpleContent mechanism to add an attribute to an element that can contain values of simple types. You can read the tutorial here. Below is another example

    Schema

    <xsd:complexType name="SizeType">
      <xsd:simpleContent>
        <xsd:extension base="xsd:integer">
          <xsd:attribute name="system" type="xsd:token"/>
        </xsd:extension>
      </xsd:simpleContent>
    </xsd:complexType>
    

    Example

    <size system="US-DRESS">10</size>