Friday, April 25, 2008

Castor Xml mapping: mapping.loadMapping() gives IOException for filepath

This is very know problem i think and many of you know it but then also i am writing it here.

For convert a Value Object class directly in pre-defined XML format we use castor mapping.We give xml mapping file (as we have seen in earlier tutorial) to Mapping class object as below which will write xml string in strWriter object from Object obj.
Mapping mapping = new Mapping();
mapping.loadMapping(mappingXmlFilename);
strWriter = new StringWriter();
Marshaller marshaller = new Marshaller(strWriter);
marshaller.setMapping(mapping);
marshaller.marshal(obj);
But when i given directly the filename to loadMapping method, it gives IOException as below:
IOException : \shared\p1\p2\shared\p1\p2\lai-sup-mapping.xml
i have given absolute filepath '\\shared\p1\p2\lai-sup-mapping.xml' and then also it is generating it using relative one.So throwing IOException for file.

Then i have changed the thing and instead of giving filepath, i have made a org.xml.sax.InputSource object from the xml file and passed that xml source to loadMapping() as below:

Mapping mapping = new Mapping();
InputSourcemappingSource =
newInputSource(new FileInputStream(mappingXmlFilename));

mapping.loadMapping(mappingSource);
strWriter = new StringWriter();
Marshaller marshaller = new Marshaller(strWriter);
marshaller.setMapping(mapping);
marshaller.marshal(obj);
And its working fine.Now its generating correct XML file from the given Value object.

0 Comments: