2011-03-31 78 views
1

我使用JAXB编组将对象封到System.out如下:JAXB编组&unmarsharller

JAXBContext ctxt = JAXBContext.newInstance(CONTEXT); 
Marshaller m = ctxt.createMarshaller(); 
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
m.marshal(map, System.out); 

则输出保存到x.xml文件为:

<?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> 

下一个I产生从这个x.xml作为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> 

最后,我试图来解读和验证x.xml文件对x.xsd如下:

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); 

但抱怨:

javax.xml.bind.UnmarshalException 
- with linked exception: 
[org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'ns2:sourceCategoryMap'.] 
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315) 

人知道什么是错在这里?非常感谢!

回答

0

不要从XML生成XSD。请求JAXB使用schemagen命令从您的java代码生成它。

+0

通过运行schemagen工具。 – bmargulies 2011-04-05 00:32:18