Link to home
Start Free TrialLog in
Avatar of ronyosi
ronyosi

asked on

Processing xsd file with JAXB

Hello!

I would like to process an xsd file using JAXB and get to the first element to find its name (in the schema itself. How would I go about doing this in JAXB? It should be a few lines of code...

So far I have:

package blog.jaxb.validation;   
import java.io.File; 
import javax.xml.XMLConstants; 
import javax.xml.bind.JAXBContext; 
import javax.xml.bind.Unmarshaller; 
import javax.xml.validation.Schema; 
import javax.xml.validation.SchemaFactory;   
public class UnmarshalDemo 
{       
	public static void main(String[] args) throws Exception {         
		SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);          
		Schema schema = sf.newSchema(new File("customer.xsd"));            
		JAXBContext jc = JAXBContext.newInstance(Customer.class);           
		Unmarshaller unmarshaller = jc.createUnmarshaller();         
		unmarshaller.setSchema(schema);         
		unmarshaller.setEventHandler(new MyValidationEventHandler());         
		Customer customer = (Customer) unmarshaller.unmarshal(new File("input.xml"));     
	}   
} 

Open in new window


Thing is, all the examples that I saw are for using the xsd to validate xml. Here what I am trying to do is access the information in the schema itself!

thanks,
Ron
Avatar of GenroseSusai
GenroseSusai
Flag of United States of America image

For e.g...  


JAXBElement<?> poElement =
   JAXBElement<?>)u.unmarshal(
      new FileInputStream( "input.xml" ) );
   SomeType st = (
      SomeType)poElement.getValue();
   SomeField field = st.getSomeField();  
Avatar of ronyosi
ronyosi

ASKER

Hi,

Thanks for the reply :)
How do I avoid this SomeType/SomeField.
Note that the schemas that I will be loading are somewhat random and only have in common that specific tag that I am trying to inspect. Therefore the
"JAXBContext jc = JAXBContext.newInstance(Customer.class); "
and
SomeField/SomeType does not work because java does not know what that is...

Ron
Avatar of Mick Barry
ASKER CERTIFIED SOLUTION
Avatar of ronyosi
ronyosi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ronyosi

ASKER

thanks everyone for your help. I found an answer on google that showed me why to pick DOM4J that it is actually less expensive in terms of memory/computation.