JAXB marshaller& unmarsharller

时间:2011-03-31 23:59:25

标签: java jaxb jaxb2

我使用JAXB marshaller将对象封送到System.out,如下所示:

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>

接下来,我从这个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.xsd的x.xml文件,如下所示:

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)
谁知道这里有什么问题?非常感谢!

1 个答案:

答案 0 :(得分:0)

不要从XML生成XSD。让JAXB使用schemagen命令从java代码生成它。