Thursday, July 21, 2011

JAXB and having not to use targetNamespace in XSD file

Recently, I had to parse a XML document using JAXB APIs. The XML document actually didn't have any namespace to it. Now for this no-namespace XML document, I wanted to come up with a XSD file.

Typically, any XSD file will look something like this,
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<xs:schema version="1.0" targetNamespace="http://ns.namespace.com/"
xmlns:ns="http://ns.namespace.com/"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <xs:element name="Root">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="Name" type="xs:string"/>
    <xs:element name="Value" type="xs:float"/>
    <xs:element name="Description" type="xs:string"/>
    <xs:element name="Author" type="xs:string"/>
   </xs:sequence>
  </xs:complexType>
 </xs:element>


For this the XML document will look something like this,

<ns:Root xmlns:ns="http://ns.namespace.com/">
 <Name>string</Name>
 <Value>123.5</Value>
 <Descritpion>string</Descritpion>
 <Author>string</Author>
</ns:Root>


But if I don't want to use any namespace, here is how the XSD should look like,
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <xs:element name="Root">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="Name" type="xs:string"/>
    <xs:element name="Value" type="xs:float"/>
    <xs:element name="Description" type="xs:string"/>
    <xs:element name="Author" type="xs:string"/>
   </xs:sequence>
  </xs:complexType>
 </xs:element>


For this the XML document will look something like this,

<Root>
 <Name>string</Name>
 <Value>123.5</Value>
 <Descritpion>string</Descritpion>
 <Author>string</Author>
</Root>


JAXB's marshaller and unmarshaller work fine with above approach.

No comments:

Post a Comment