I use JAXB marshaller to marshal an object to System.out as following:
JAXBContext ctxt = JAXBContext.newInstance(CONTEXT);
Marshaller m = ctxt.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(map, System.out);
then save the output into x.xml file as:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:sourceCategoryMap xmlns:ns2="http://schemas.xyz.com/services/1.0">
<ns2:source-category-map>
<entry>
<key>Seattle</key>
<map>
<entry>
<key>Restaurant</key>
<value>Restaurant</value>
</entry>
<entry>
<key>Fun</key>
<value>Entertainment</value>
</entry>
</map>
</entry>
<entry>
<key>Honolulu</key>
<map>
<entry>
<key>Food</key>
<value>Restaurant</value>
</entry>
</map>
</entry>
</ns2:source-category-map>
</ns2:sourceCategoryMap>
next i generated the schema file from this x.xml as x.xsd:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:ns2="http://schemas.xyz.com/services/1.0">
<xs:import namespace="http://schemas.xyz.com/services/1.0" schemaLocation="ns2.xsd"/>
<xs:element name="entry">
<xs:complexType>
<xs:sequence minOccurs="0">
<xs:choice maxOccurs="unbounded">
<xs:element ref="key"/>
<xs:element ref="map"/>
</xs:choice>
<xs:element ref="value"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="key" type="xs:string"/>
<xs:element name="map">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="entry"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="value" type="xs:NCName"/>
</xs:schema>
Last i tried to unmarshall and validate x.xml file against the x.xsd as following:
Unmarshaller um = MarshalUtils.getUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(
javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(SOURCE_REGION_SCHEMA));
um.setSchema(schema);
SourceRegionMap srm = (SourceRegionMap) um.unmarshal(input);
but it complained:
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException开发者_C百科: cvc-elt.1: Cannot find the declaration of element 'ns2:sourceCategoryMap'.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315)
anyone know what's wrong here? Much Thanks!
Don't generate an XSD from the XML. Ask JAXB to generate it from your java code using the schemagen command.
精彩评论